天天看點

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的析構函數
}