Ownership is Rust's most defining feature—it enables memory safety without garbage collection. Understanding ownership is crucial to mastering Rust.
The Three Ownership Rules
Each value has one owner
You can transfer ownership (move)
When the owner goes out of scope, the value is dropped
Basic Ownership
fnmain() {
let = ::(\
s1
String
from
"hello\"); // s1 owns the String
let s2 = s1; // Ownership moves to s2
// println!(\"s1: {}\", s1); // ERROR! s1 no longer owns the data
println!(\"s2: {}\", s2); // OK
}
When s2 = s1 executes, ownership transfers. s1 is no longer valid.
Stack vs Heap
Understanding ownership requires knowing where data lives:
Stack
Fixed-size, fast, automatic cleanup. Stores simple types and references.
letx = 5; // Stack: integerlety = x; // Stack: copies the valueprintln!(\"x: {}, y: {}\", x, y); // Both valid (integers are Copy)
Heap
Variable-size, allocated at runtime. Stores complex types.
lets = String::from(\"hello\"); // Data on heap, pointer on stack
letx = 5;
lety = x; // Copies the value (not move)println!(\"x: {}, y: {}\", x, y); // Both valid
Types that implement Copy: integers, floats, booleans, chars (and tuples of these).
Functions and Ownership
Passing values to functions also transfers ownership:
fntakes_ownership(s: String) {
println!(\"{}\", s);
} // s goes out of scope, String is dropped
fn main() {
let s = String::from(\"hello\");
takes_ownership(s); // Ownership transferred
// println!(\"s: {}\", s); // ERROR!
}
Return Ownership
Functions can return ownership:
fnreturn_string() ->String {
String::from(\"hello\")
}
fn main() {
let s = return_string(); // Ownership transferred to s
println!(\"s: {}\", s); // OK
}
Practical Example
fnget_length(s: String) -> (String, usize) {
letlen = s.len();
(s, len) // Return both String and its length
}
fnmain() {
lets = String::from(\"hello\");
let (s, len) = get_length(s); // Reclaim ownership
println!(\"The string '{}' has length {}\", s, len);
}
This pattern is tedious—that's where borrowing comes in (next lesson).
Memory Safety Benefits
Ownership prevents:
Use-after-free: Can't use freed memory
Double-free: Each value has one owner
Data races: Clear responsibility for cleanup
The compiler enforces all of this at compile time, with zero runtime cost.
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities