Rather than relying on garbage collection or user memory allocation (via allocate/free memory), Rust relys on the compiler to ensure memory is managed through ownership.
Ownership is a set of rules that governs how a Rust program manages memory.
Ownership helps with organizing how data is stored in the heap, minimizing duplication of data in the heap and cleaning up the heap. Data types (e.g. Scalar types) are not stored in the heap. Data types (e.g. integers) can be easily pushed/stored and popped/removed on the stack. Rust enforces single ownership.
via Rust-lang Book
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
via Colin's Notes
- By default, values on the heap may only bind to one variable at a time
- Value reassignment / copying moves ownership by default, even for stack allocated data
- Passing variables to functions moves Ownership by default.
- Pass-by-reference, known as “borrowing” prevents ownership moves
- Variables are imutible by default
Rust calls drop automatically at the closing curly bracket.
Rust is different from other languages in which any assignment or function passing ends the scope of the variable unless cloned or copied because the ownership of the variable.
let s1 = String::from("hello");
let s2 = s1; // the scope of s1 has ended and s1 has been dropped
println!("{}, world!", s1);
let s1 = String::from("hello");
let s2 = some_func(s1); // the scope of s1 has ended and s1 has been dropped
println!("{}, world!", s1);
- variable is assigned (=)/moved/copied to another variable
- variable is passed to a function
- variable is no longer in scope as specified by {}
- variable is returned from a function References 3 has great examples on this.
Ampersand &
are referred to as references and allow a value to be referred to without taking ownership. A referene value can not be modified. References are immutable by default. Using a reference as a function parameters is called borrowing.
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid.