I have seen a build function called drop(T) in rust, basically, it moves the given variable.
let's say if we have code as follow:
struct Obj {
a: i32,
}
impl Drop for Obj {
fn drop(&mut self) {
println!("> Dropping {}", self.a);
}
}
fn main() {
let mut m = &Obj { a: 5 };
m = &Obj { a: 6 };
m = &Obj { a: 7 };
m = &Obj { a: 8 };
let t = thread::spawn(|| {
for i in 0..5 {
println!("Counting {}", i);
thread::sleep(Duration::from_secs_f32(1.0));
}
});
t.join().unwrap();
}
The Result is :
> Dropping 6
> Dropping 7
> Dropping 8
Counting 0
Counting 1
Counting 2
Counting 3
Counting 4
> Dropping 5
As the result shows the 6 to 8 has been collected just after resignments, the origin 5 is lasting until the end of main. why the 5 is not collected in the first place?