Junior — Middle
Can you explain how memory management and allocation are handled in Rust?
sobes.tech AI
Answer from AI
In Rust, memory management is based on the ownership, borrowing, and lifetimes system, which allows avoiding the need for a garbage collector while ensuring memory safety.
- Ownership: Each object in Rust has a single owner — a variable responsible for freeing the memory.
- Borrowing: You can temporarily take a reference to data without transferring ownership. Borrows can be mutable or immutable, with either multiple immutable references or one mutable reference at a time.
- Lifetimes: The compiler checks that references do not outlive the data they refer to.
Example:
fn main() {
let s = String::from("hello"); // s owns the string
let r1 = &s; // immutable reference
let r2 = &s; // another immutable reference
println!("{} and {}", r1, r2);
// let r3 = &mut s; // error: cannot have a mutable reference while immutable references exist
}
Thus, Rust guarantees memory safety at compile time without runtime overhead.