fn essential() {
let mut information = Field::new(1);
{
information = 3;
let mut other_data = Field::new(2);
}
}
When this code runs, other_data
shall be heap-allocated contained in the scope, after which routinely de-allocated when it leaves. The identical goes for information
: it’ll be created contained in the scope of the essential()
operate, and routinely disposed of when essential()
ends. All that is seen to the compiler at compile time, so errors involving scope don’t compile.
Possession in Rust
Rust provides one other key concept to scoping and RAII: the notion of possession. Objects can solely have one proprietor, or reside reference, at a time. You possibly can transfer the possession of an object between variables, however you’ll be able to’t discuss with a given object mutably in multiple place at a time.
fn essential() {
let a = Field::new(5);
let _b = a;
drop(a);
}
On this instance, we create the worth in a
with a heap allocation, then assign _b
to a
. By doing this, we’ve moved the worth out of a
. So, if we attempt to manually deallocate the worth with drop()
, we get an error: use of moved worth: `a
. Change the final line to drop(_b)
, although, and every part is ok. On this case, we’re manipulating that worth by the use of its present, legitimate proprietor.