[][src]Function tao_of_rust::ch07::structs::drop_order

pub fn drop_order()

结构体: 析构顺序

Base usage: 本地变量

struct PrintDrop(&'static str);
    impl Drop for PrintDrop {
        fn drop(&mut self) {
            println!("Dropping {}", self.0)
    }
}
fn main() {
    let x = PrintDrop("x");
    let y = PrintDrop("y");
}Run

Base usage: 元组

struct PrintDrop(&'static str);
    impl Drop for PrintDrop {
        fn drop(&mut self) {
            println!("Dropping {}", self.0)
    }
}
fn main() {
    let tup1 = (PrintDrop("a"), PrintDrop("b"), PrintDrop("c"));
    let tup2 = (PrintDrop("x"), PrintDrop("y"), PrintDrop("z"));
}Run

Base usage: 元组,携带panic!的元素

struct PrintDrop(&'static str);
    impl Drop for PrintDrop {
        fn drop(&mut self) {
            println!("Dropping {}", self.0)
    }
}
fn main() {
    let tup1 = (PrintDrop("a"), PrintDrop("b"), PrintDrop("c"));
    let tup2 = (PrintDrop("x"), PrintDrop("y"), panic!());
}Run

Base usage: 闭包捕获变量

struct PrintDrop(&'static str);
    impl Drop for PrintDrop {
        fn drop(&mut self) {
            println!("Dropping {}", self.0)
    }
}
fn main() {
    let z = PrintDrop("z");
    let x = PrintDrop("x");
    let y = PrintDrop("y");
    let closure = move || { y; z; x; };
}Run

Base usage: 闭包捕获变量,包含内部作用域

struct PrintDrop(&'static str);
    impl Drop for PrintDrop {
        fn drop(&mut self) {
            println!("Dropping {}", self.0)
    }
}
fn main() {
    let y = PrintDrop("y");
    let x = PrintDrop("x");
    let z = PrintDrop("z");
    let closure = move || {
        { let z_ref = &z; }
        x; y; z;
    };
}Run

Base usage: 结构体析构顺序

struct PrintDrop(&'static str);

impl Drop for PrintDrop {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

struct Foo {
    bar: PrintDrop,
    baz: PrintDrop,
}

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Dropping Foo")
    }
}

fn main() {
    let foo = Foo {
        bar: PrintDrop("bar"),
        baz: PrintDrop("baz"),
    };
}Run

Base usage: 结构体和枚举析构顺序

struct PrintDrop(&'static str);
impl Drop for PrintDrop {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}
enum E {
    Foo(PrintDrop, PrintDrop),
}
struct Foo {
    x: PrintDrop,
    y: PrintDrop,
    z: PrintDrop,
}
fn main() {
    let e = E::Foo(PrintDrop("a"), PrintDrop("b"));
    let f = Foo {
        x: PrintDrop("x"),
        y: PrintDrop("y"),
        z: PrintDrop("z"),
    };
}Run