You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Ownership is Rust's most distinctive feature and the key to its memory safety guarantees. Understanding ownership, moves, references, and borrowing is essential for writing Rust programs.
Rust enforces three ownership rules at compile time:
{
let s = String::from("hello"); // s owns the String
// s is valid here
} // s goes out of scope — the String is dropped (freed)
When you assign a heap-allocated value to another variable, ownership moves:
let s1 = String::from("hello");
let s2 = s1; // s1 is MOVED to s2
println!("{s1}"); // ERROR: s1 is no longer valid
println!("{s2}"); // OK: s2 owns the String
This prevents double free errors — only one variable can free the memory.
Types that are small and live on the stack implement the Copy trait. Assignment copies instead of moves:
let x = 5;
let y = x; // x is COPIED, not moved
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.