Created
June 29, 2020 01:18
-
-
Save junha1/a26965e12d32cf26206aca3c7bd3156e to your computer and use it in GitHub Desktop.
dropping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Option1 - Explicit destruction | |
// | |
struct A; | |
struct B; | |
impl A { | |
fn shutdown(self) { | |
println!("Do some destruction"); | |
} | |
} | |
impl Drop for A { | |
fn drop(&mut self) { | |
panic!("You must have called shutdown() before") | |
} | |
} | |
impl B { | |
fn shutdown(self) { | |
println!("Do some destruction"); | |
} | |
} | |
impl Drop for B { | |
fn drop(&mut self) { | |
panic!("You must have called shutdown() before") | |
} | |
} | |
struct S { | |
a: Option<A>, | |
b: Option<B> | |
} | |
impl S { | |
fn shutdown(mut self) { | |
self.a.take().unwrap().shutdown(); | |
self.b.take().unwrap().shutdown(); | |
} | |
} | |
impl Drop for S { | |
fn drop(&mut self) { | |
panic!("You must have called shutdown() before") | |
} | |
} | |
// | |
// Option2 - Implicit destruction | |
// | |
struct A_; | |
struct B_; | |
impl Drop for A_ { | |
fn drop(&mut self) { | |
println!("Do some destruction"); | |
} | |
} | |
impl Drop for B_ { | |
fn drop(&mut self) { | |
println!("Do some destruction"); | |
} | |
} | |
struct S_ { | |
a: A_, | |
b: B_, | |
} | |
// no need to impl Drop for S_ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment