Rust 如何延迟未命名对象的销毁?
我正在使用创建和删除磁盘上的文件夹。除了构造之外,代码中未引用Rust 如何延迟未命名对象的销毁?,rust,Rust,我正在使用创建和删除磁盘上的文件夹。除了构造之外,代码中未引用TempDir本身 由于编译器警告未使用的对象,我尝试(取消)将TempDir结构命名为。,但这会导致结构立即被销毁 有什么好的解决办法吗 请参阅,将one与two进行比较: pub struct Res; impl Drop for Res { fn drop(&mut self) { println!("Dropping self!"); } } fn one() { printl
TempDir
本身
由于编译器警告未使用的对象,我尝试(取消)将TempDir结构命名为。
,但这会导致结构立即被销毁
有什么好的解决办法吗
请参阅,将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();
}
pub-struct-Res;
对Res的impl Drop{
fn下降(&mut自我){
println!(“放下自我!”);
}
}
fn一(){
println!(“一”);
让r=Res;//为变量指定名称,但在名称前加下划线会延迟销毁,直到作用域结束,但不会触发未使用变量警告
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");
}
}
删除
在第一个作用域结束之前
在第二个作用域结束之前
滴水
使用\u未使用\u但\u编译器\u不会\u抱怨\u,因为\u前导\u下划线的\u应仍然有效