我正在使用 TempDir
struct在磁盘上创建和删除文件夹。除了构造之外,TempDir
本身在代码中未被引用。
由于编译器对未使用的对象发出警告,我尝试(取消)将 TempDir 结构命名为 _
,但这导致该结构立即被销毁。
有好的解决办法吗?
参见 example code , 比较 one
和 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();
}
最佳答案
为变量命名但在名称前加下划线会延迟销毁直到范围结束,但不会触发未使用变量警告。
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/