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


Video address

Headline address:…
Station B address:

Source address

GitHub address:…

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