• Sun. Apr 13th, 2025

Rust memory management explained | InfoWorld

Byadmin

Feb 12, 2025



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 de-allocated when it leaves. The same goes for data: it’ll be created inside the scope of the main() function, and automatically disposed of when main() ends. All 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 only have one owner, or live reference, at a time. You can move the ownership of an object between variables, but you can’t refer to a given 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.



Source link