Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 18, 2021 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/52c8008765b3170cd3ed3ab17128b060 to your computer and use it in GitHub Desktop.
Save rust-play/52c8008765b3170cd3ed3ab17128b060 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
struct Hoge {
id: usize,
ok: bool,
}
impl Drop for Hoge {
fn drop(&mut self) {
assert!(self.ok, "must call .ok() (id: {})", self.id);
}
}
impl Hoge {
fn new(id: usize) -> Self {
Self { id, ok: false }
}
fn next(mut self, check: i32) -> Result<Self, ()> {
self.ok = true;
if check < 10 {
Ok(Self {
id: self.id,
ok: false,
})
} else {
Err(())
}
}
fn ok(mut self, check: i32) -> Result<(), ()> {
self.ok = true;
if check < 10 {
Ok(())
} else {
Err(())
}
}
}
pub fn run() -> Result<(), ()> {
let h0 = Hoge::new(0);
let h1 = Hoge::new(1);
let h2 = Hoge::new(3);
let h3 = Hoge::new(4);
h0.next(3)?;
h1.next(4)?.next(9)?.ok(3)?;
h2.next(10)?.next(4)?.ok(3)?;
h3.ok(4)?;
Ok(())
}
#[cfg(test)]
mod test {
#[test]
fn it_works() {
super::run().unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment