20 July 2023

Rust Memory Management - Part 1

Rust is a very different language. It doesn’t use a garbage collector, but users don’t have to worry about allocating/freeing memory. Rust is blazing fast, but you may often need to wrestle with the compiler to get things right. It’ll help a lot if you understand how Rust manages the memory.

If a variable is defined and it’s size can be determined at compile time, it’ll be stored in the stack

let x: i32 = 1;
let color = RGBColor{r: 100, g: 100, b: 100};

var in stack

If a variable is stored in the stack, and you try to assign it to another variable. If the type of the variable implements the Copy trait, it’s value will be copied (stored in stack as well) and assigned to the new variable.

let x: i32 = 1;
let y = x;
println!("{}", x);
println!("{}", y);

var in stack

If the variable doesn’t implement the Copy trait, it’s value will be copied and assigned to the new variable, but the old variable will be marked as moved and will be dropped once it’s out of scope.

let x: RGBColor{r: 100, g: 100, b: 100};
let y = x;
println!("{}", y);
println!("{}", x); // compile error, x has been marked as moved and will be dropped once it's out of scope

var in stack

tags: Rust