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


Video address

Headline address:…
Station B address:

Source address

GitHub address:…

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

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