Skip to content

Instantly share code, notes, and snippets.

@junha1
Created June 29, 2020 01:18
Show Gist options
  • Save junha1/a26965e12d32cf26206aca3c7bd3156e to your computer and use it in GitHub Desktop.
Save junha1/a26965e12d32cf26206aca3c7bd3156e to your computer and use it in GitHub Desktop.
dropping
//
// 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