如何延迟未命名对象的销毁?

Pur*_*reW 4 rust

我正在使用该TempDir结构在磁盘上创建和删除文件夹。在TempDir本身不从它的建筑除了代码中引用。

由于编译器对未使用的对象发出警告,我尝试(取消)将 TempDir-struct 命名为,_但这会导致该结构立即被销毁。

有没有很好的解决方案?

示例代码,比较onetwo

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();
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 5

为变量命名但在名称前加上下划线会将销毁延迟到作用域结束,但不会触发未使用的变量警告。

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");
    }
}
Run Code Online (Sandbox Code Playgroud)
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");
    }
}
Run Code Online (Sandbox Code Playgroud)