010 Rust死靈書之Drop檢查

linghuyichong發表於2021-02-17

本系列錄製的影片主要放在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 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章