天天看点

017 Rust死灵书之Drop标志

介绍

本系列录制的视频主要放在B站上​​Rust死灵书学习视频​​

Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source

drop标志

#[derive(Debug)]

struct Droppable {
    name: &'static str,
}

impl Drop for Droppable {
    fn drop(&mut self) {
        println!("> Dropping {}", self.name);
    }
}

fn main() {
    let a = Droppable { name: "a" }; //a未初始化,仅仅覆盖值

    let b = a; //b未初始化,仅仅覆盖值
    let mut c = Droppable { name: "c" };
    println!("c = {:#?}", c);

    c = b; //c已经初始化,需要调用drop函数,再覆盖值
    println!("c = {:#?}", c);

    println!("Hello, world!");
    //离开花括号,调用a的析构函数
}