fn main() {
let mut data = Box::new(1);
{
data = 3;
let mut other_data = Box::new(2);
}
}
When this code runs, other_data
will be heap-allocated inside the scope, and then automatically deallocated when it leaves. The same goes for data
: it will be created inside the scope of the main()
function, and automatically disposed of when main()
ends. All of this is visible to the compiler at compile time, so mistakes involving scope don’t compile.
Ownership in Rust
Rust adds another key idea to scoping and RAII: the notion of ownership. Objects can have only one owner, or live reference, at a time. You can move the ownership of an object between variables, but you can’t refer to an object mutably in more than one place at a time.
fn main() {
let a = Box::new(5);
let _b = a;
drop(a);
}
In this example, we create the value in a
with a heap allocation, then assign _b
to a
. By doing this, we’ve moved the value out of a
. So, if we try to manually deallocate the value with drop()
, we get an error: use of moved value: `a`
. Change the last line to drop(_b)
, though, and everything is fine. In this case, we’re manipulating that value by way of its current, valid owner.