Ownership / Move
Rust's ownership system enforces a unique rule: every value has exactly one owner. This guarantees memory safety at compile time. When the owner goes out of scope, the value is automatically freed.
Syntax
// Ownership move
let variable1 = value;
let variable2 = variable1; // Ownership of variable1 moves to variable2 (variable1 becomes invalid).
// Moving ownership into a function
fn function_name(arg: Type) { ... }
function_name(variable); // Ownership of variable moves into the function.
// Explicitly free memory
drop(variable);
Overview
| Rule | Description |
|---|---|
| Single owner | Each value has exactly one owning variable at any given time. |
| Freed at scope end | When the owner goes out of scope, the value's memory is automatically freed. |
| Move semantics | Assignment or passing to a function moves ownership, making the original variable unusable. |
| drop() | Used to immediately free a variable that holds ownership. |
Sample Code
fn take_ownership(s: String) {
println!("{}", s);
} // s is freed here.
fn main() {
let s1 = String::from("hello");
let s2 = s1; // Ownership of s1 moves to s2.
// println!("{}", s1); // Error: s1 is no longer valid.
println!("{}", s2); // Prints "hello".
let s3 = String::from("world");
take_ownership(s3); // Ownership of s3 moves into the function.
// println!("{}", s3); // Error: s3 is no longer valid.
// Immediately free s4 with drop().
let s4 = String::from("drop me");
drop(s4);
// println!("{}", s4); // Error: s4 has already been freed.
// Types that implement the Copy trait are copied instead of moved.
let x = 5;
let y = x; // x is still valid.
println!("x={}, y={}", x, y); // Both are usable.
}
Details
Rust's ownership system guarantees memory safety without a garbage collector. When a value goes out of scope, drop() is called automatically and the memory is freed (the RAII pattern).
Using a variable after its ownership has been moved causes a compile error. If you need to use a value in multiple places, use borrowing (& references) or clone().
Types that implement the Copy trait — such as integers, floating-point numbers, booleans, and chars — are copied on assignment, so the original variable remains valid.
If you find any errors or copyright issues, please contact us.