What is Ownership in Rust?
Ownership is Rustβs core memory management system. It defines how values are stored, accessed, and cleaned up in memory without needing a garbage collector.
In simple terms: every value in Rust has a single owner, and when that owner goes out of scope, the value is automatically removed from memory.
Ownership is Rustβs way of making sure memory is cleaned up safely and predictably.
The rules of ownership
- π Each value has exactly one owner
- π When the owner goes out of scope, the value is dropped
- π You can move or borrow values, but not violate ownership rules
Basic example
fn main() { let s = String::from("hello"); println!("{ }", s); } // memory is freed here automatically
When s goes out of scope, Rust automatically frees the memory β no manual cleanup needed.
Move semantics
In Rust, assigning a value usually moves ownership instead of copying it.
fn main() { let s1 = String::from("hello"); let s2 = s1; // println!("{}", s1); β error: value moved }
After the move, s1 is no longer valid because ownership was transferred to s2.
Borrowing in Rust
Instead of transferring ownership, Rust allows you to borrow values using references.
fn calculate_length(s: &String) -> usize { s.len() } fn main() { let s = String::from("hello"); let len = calculate_length(&s); println!("Length: {}", len); }
Here, &s means we borrow the value without taking ownership.
Mutable borrowing
Rust also allows changing borrowed data using mutable references.
fn change(s: &mut String) { s.push_str(" world"); } fn main() { let mut s = String::from("hello"); change(&mut s); }
Why ownership matters
- π‘οΈ Prevents use-after-free bugs
- π‘οΈ Prevents double free errors
- π‘οΈ Prevents data races in concurrent code
- π‘οΈ Ensures memory safety at compile time
Rust achieves memory safety without a garbage collector β all thanks to ownership and borrowing.
Summary
Ownership is Rustβs system for managing memory safely and efficiently. It ensures every value has one owner, and uses moves and borrows instead of manual memory control.
In short: Ownership is how Rust guarantees memory safety at compile time.