How to delay destruction of unnamed objects?

大城市里の小女人 提交于 2021-01-27 09:34:26

问题


I am using the TempDir struct to create and remove folders on disk. The TempDir itself is not referenced in the code apart from its construction.

Since the compiler warns about unused objects, I tried (un)naming the TempDir-struct to _ but this results in the struct immediately being destroyed.

Is there a nice solution to this?

See example code, compare one to two:

pub struct Res;
impl Drop for Res {
    fn drop(&mut self) {
        println!("Dropping self!");
    }
}

fn one() {
    println!("one");
    let r = Res; // <--- Dropping at end of function 
                 //      but compiler warns about unused object
    println!("Before exit");
}

fn two() {
    println!("two");
    let _ = Res;  // <--- Dropping immediately
    println!("Before exit");
}

fn main() {
    one();
    two();
}

回答1:


Giving a variable a name but prefixing the name with an underscore delays destruction until the end of the scope but does not trigger the unused variable warning.

struct Noisy;

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("Dropping");
    }
}

fn main() {
    {
        let _ = Noisy;
        println!("Before end of first scope");
    }

    {
        let _noisy = Noisy;
        println!("Before end of second scope");
    }
}
Dropping
Before end of first scope
Before end of second scope
Dropping


来源:https://stackoverflow.com/questions/39111322/how-to-delay-destruction-of-unnamed-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!