Learn extra at:
fn major() {
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 robotically de-allocated when it leaves. The identical goes for information
: it’ll be created contained in the scope of the major()
perform, and robotically disposed of when major()
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 stay reference, at a time. You may transfer the possession of an object between variables, however you possibly can’t seek advice from a given object mutably in multiple place at a time.
fn major() {
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 all the things is ok. On this case, we’re manipulating that worth by means of its present, legitimate proprietor.