Rust programming video tutorial (Advanced) – 012_ 2 call drop in advance.

Time:2021-10-18

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Source address

GitHub address:https://github.com/anonymousGiga/learn_rus…

Explanation content

Discard the value early through STD:: MEM:: drop. When cleaning in advance is required, instead of directly calling the drop method, the STD:: MEM:: drop method is called, for example:

struct Dog {
    name: String,
}

//The following is a drop trait implementation for dog
impl Drop for Dog {
    fn drop( &mut self ) {
        println!("Dog leave");
    }
}

fn main() {
    let a = Dog { name: String::from("wangcai")};
    let b = Dog { name: String::from("dahuang")};
    //a.drop();// Error, drop cannot be called directly
    drop(a);// Correct, the cleanup is displayed through STD:: MEM:: drop
    println!("At the end of main");
}

The printing order of the above example will be:

Dog leave // call drop (a) to print
At the end of main
Dog leave

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed