Ownership Basics
Understand the central Rust concept that makes memory safety possible.
Learning objectives
- Explain ownership in simple terms
- Understand move behavior
- Recognize why ownership prevents common memory errors
What Is Ownership?
Ownership is Rust’s system for managing memory. Every value has one owner. When the owner goes out of scope, the value is cleaned up automatically.
Move Behavior
When a value such as a String is assigned to another variable, ownership may move. After the move, the original variable can no longer be used.
Why It Matters
Ownership helps prevent double-free errors, dangling references, and other memory problems before the program runs.
Example code
fn main() {
let first = String::from("Rust");
let second = first;
println!("Second value: {}", second);
// println!("{}", first); // This would not compile because ownership moved.
}
Practice task: Create a String variable, move it to another variable, and print the new owner.