问题
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