010 drop check of rust Necromancer

Time:2021-4-25

introduce

The video recorded in this series is mainly on station BRust necromancer learning video

The source code of rust is as follows:github.com/anonymousGiga

Note content

A piece of code

struct Inspector<'a>(&'a u8);

struct World<'a> {
    inspector: Option<Inspector<'a>>,
    days: Box<u8>,
}

fn main() {
    let mut world = World {
        inspector: None,
        days: Box::new(1),
    };
    world.inspector = Some(Inspector(&world.days));
}

Add drop:

struct Inspector<'a>(&'a u8);

impl<'a> Drop for Inspector<'a> {
    fn drop(&mut self) {
        println!("I was only {} days from retirement!", self.0);
    }
}

struct World<'a> {
    inspector: Option<Inspector<'a>>,
    days: Box<u8>,
}

fn main() {
    let mut world = World {
        inspector: None,
        days: Box::new(1),
    };
    world.inspector = Some(Inspector(&world.days));
}

Drop requirements

A type that implements drop safely, itsGeneric parametersThe life cycle must be strictly longer than itself.
PS: note that it is a generic type. If it is not a generic type, then only static is used

But the following code doesn’t work:

//struct Inspector<'a>(&'a u8);

struct Inspector<'a>(&'a u8, &'static str);



//impl<'a> Drop for Inspector<'a> {

unsafe impl<'#[may_dangle] a> Drop for Inspector<'a> {

    fn drop(&mut self) {

        //println!("I was only {} days from retirement!", self.0);

        println!("I was only {} days from retirement!", self.1);
    }
}


struct World<'a> {
    inspector: Option<Inspector<'a>>,
    days: Box<u8>,
}

fn main() {
    let mut world = World {
        inspector: None,
        days: Box::new(1),
    };

    //world.inspector = Some(Inspector(&world.days, "hello"));

    world.inspector = Some(Inspector(&world.days, "gadget"));
}

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong