There is a vector resource that is allocated in line 2 of the program below. When the program ends, the vector resource is not owned. If a resource is not owned at all, when does it get reclaimed? Is there an explanation using the terminology of Rust ownership semantics and lifetimes that could convince a programmer that this resource is indeed reclaimed?
fn main() {
let mut v = vec![1,2];
v = vec![3, 4];
}
In Rust terms, an item is dropped when it goes out of scope, which often (but not always) corresponds to the end of a block. When it is dropped, any resources that are part of the item are also released.
Resources can mean memory, as in the vector example, but it can also correspond to other things like a file handle or a lock. This is commonly referred to as Resource Acquisition Is Initialization (RAII).
You can never convince someone who truly doesn't want to believe ^_^. However, you can implement
Drop
yourself to see when an item is being dropped:This will have the output
You can see that the first variable is dropped when its binding is replaced as there's no longer any way to get to the
NoisyDrop(1)
value. The second variable is dropped when it goes out of scope due to the method ending.Consider this example:
Conceptually, it could be written as
And this example
Could be rewritten as
These rewritings show the lifetime of each variable. Whenever you call a method with a generic lifetime parameter, the lifetime of the block will be the concrete value that gets substituted for the
'a
generic.