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

标签 rust

我正在使用 TempDir struct在磁盘上创建和删除文件夹。除了构造之外,TempDir 本身在代码中未被引用。

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

有好的解决办法吗?

参见 example code , 比较 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();
}

最佳答案

为变量命名但在名称前加下划线会延迟销毁直到范围结束,但不会触发未使用变量警告。

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

关于rust - 如何延迟未命名对象的销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39111322/

相关文章:

rust - 在为引用和非引用类型实现一个特性时,我是否必须实现它两次?

Rust - 单行内的条件变异

exception - 如何从调用堆栈中的多个层返回?

stream - 使用 nickel.rs 读取请求正文

rust - 临时值的生命周期不够长

linux - 如何使用gdk和Rust获取当前事件窗口的标题?

rust - 跨任务和闭包的 DuplexStream

reference - 有没有办法返回对函数中创建的变量的引用?

reference - 为什么我需要为返回引用的函数添加生命周期?

c - 语句 "Rust won' t convert integers to references"是什么意思?