一般来讲,变量的析构顺序和声明顺序相反,但是并不是所有的情况都是这样。

本地变量

本地变量先声明后析构。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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");
}
1
2
Dropping y
Dropping x

元组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
struct PrintDrop(&'static str);
impl Drop for PrintDrop {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

fn main() {
    let _tup1 = (PrintDrop("x"), PrintDrop("y"));
    let _tup2 = (PrintDrop("s"), PrintDrop("z"));
}
1
2
3
4
Dropping s
Dropping z
Dropping x
Dropping y

先析构 tup2 ,后析构 tup1 ,在元组内部是前面的先析构,后面的后析构。

结构体和枚举体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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"),
    };
}
1
2
3
4
5
Dropping x
Dropping y
Dropping z
Dropping a
Dropping b

闭包捕获变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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 || {
        drop(y);
        drop(z);
        drop(x);
    };
}
1
2
3
Dropping y
Dropping z
Dropping x

闭包内的析构与捕获顺序相同,先捕获的先析构。