Rust programming video tutorial (Advanced) – 012_ 1drop trail introduction

Time:2021-10-19

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

1. Drop trait is similar to the destructor in other languages. It executes the code of this function when the value leaves the scope.
You can provide the implementation of drop trait for any type (but note that the types here need to be included in struct, and use examples to implement drop for I32 and drop for string error reporting).

2. Implement drop trait
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")};
    println!("At the end of main");
}
//It can be seen from the print result that the drop method was called when leaving the scope.

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

Linghu rushed