010 Rust死灵书之Drop检查

介绍

本系列录制的视频主要放在B站上Rust死灵书学习视频

Rust相关的源码资料在:github.com/anonymousGiga

笔记内容

一段代码

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));
}

加上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要求

一个安全地实现 Drop的类型,它的泛型参数生命周期必须严格地长于它本身。
ps:注意是泛型类型,如果不是泛型类型,则只有用static了

但是如下的代码是不行的:

//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"));
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!