Mastering Ownership and Movement in Rust: A Comprehensive Guide
Mastering Ownership and Movement in Rust: A Comprehensive Guide
This document from the Rust programming language's official documentation explains the fundamental concepts of ownership, movement, and mutability within variable scopes.
Key Concepts
1. Ownership
- In Rust, every value has a single owner.
- When the owner goes out of scope, the value is dropped (memory is freed).
2. Movement
- When you assign a variable to another variable, the ownership of the value is transferred (moved) from the original variable to the new one.
- The original variable can no longer be used after the move.
3. Mutability
- Variables in Rust are immutable by default.
- To allow a variable's value to be changed, you must declare it as mutable using the
mut
keyword.
Examples
Example of Movement
fn main() {
let x = String::from("hello"); // x owns the String
let y = x; // y takes ownership of the String
// println!("{}", x); // This line would cause a compile error
println!("{}", y); // This works, y owns the String
}
In this example, x
initially owns the String
. When y
is assigned x
, y
becomes the new owner, and x
can no longer be used.
Example of Mutability
fn main() {
let mut s = String::from("hello"); // s is mutable
s.push_str(", world!"); // we can change the value of s
println!("{}", s); // Outputs: hello, world!
}
Here, s
is declared as mutable, allowing us to modify its contents with push_str
.
Summary
- Understanding ownership and movement is crucial for managing memory safely in Rust.
- Always keep in mind the ownership rules when transferring data and be explicit about mutability when changes are needed.