Ownership: The One Rule That Makes Rust Different From Everything Else
Not a medium member yet? Read it here for free
Welcome back to Zero to Rust! This article provides a comprehensive exploration of Rust’s ownership system, covering ownership, borrowing, and lifetimes. Understanding these concepts is fundamental to writing safe, efficient, and idiomatic Rust code.
Part 1: Ownership
1.1 The Ownership Principle
Rust’s ownership system is built upon three core principles:
- Single Owner Principle: Every value in Rust has a single, unique owner at any given time.
- Scope Linked Lifetime: When an owner goes out of scope, the value it owns is automatically dropped (deallocated). This prevents memory leaks and dangling pointers.
- Move Semantics: By default, assigning a value to another variable moves ownership. The original variable is no longer valid after the move.
fn main() {
let s1 = String::from("Deep Space"); // s1 owns the String
let s2 = s1; // Ownership MOVED to s2. s1 is now invalid.
// println!("{}", s1); // Compiler Error! s1 no longer owns the data.
println!("{}", s2); // "Deep Space" - valid owner
} // The String data is dropped when s2 goes out of scope.
fn main() {
let s1 = String::from("Deep Space"); // s1 owns the String
let s2 = s1; // Ownership MOVED to s2. s1 is now invalid.
// println!("{}", s1); // Compiler Error! s1 no longer owns the data.
println!("{}", s2); // "Deep Space" - valid owner
} // The String data is dropped when s2 goes out of scope.
1.2 Stack vs. Heap: Where Data Lives
Understanding how data is stored is crucial for grasping ownership.
- Stack: Fixed-size data (integers, booleans, characters, tuples of Copy types) resides on the stack. Stack allocation is fast and efficient. Values on the stack implement the
Copytrait. Assignment creates a copy, leaving the original variable valid.
let x = 5; // Stack-allocated integer
let y = x; // Copy occurs. Both x and y are valid.
println!("x: {}, y: {}", x, y); // Output: x: 5, y: 5
let x = 5; // Stack-allocated integer
let y = x; // Copy occurs. Both x and y are valid.
println!("x: {}, y: {}", x, y); // Output: x: 5, y: 5
- Heap: Dynamically sized data (Strings, Vectors, custom types) is stored on the heap. Heap allocation is more flexible but slightly slower. Values on the heap generally do not implement the
Copytrait. Assignment moves ownership.
let s1 = String::from("Black Hole"); // Heap-allocated String
let s2 = s1; // Ownership transferred. s1 is now invalid.
// println!("{}", s1); // Compiler error! s1 is no longer valid.
println!("{}", s2); // Output: Black Hole
let s1 = String::from("Black Hole"); // Heap-allocated String
let s2 = s1; // Ownership transferred. s1 is now invalid.
// println!("{}", s1); // Compiler error! s1 is no longer valid.
println!("{}", s2); // Output: Black Hole
1.3 Cloning for Deep Copies
When you need a true, independent copy of heap-allocated data, use the clone() method. This creates a deep copy of the data on the heap.
let s1 = String::from("Event Horizon");
let s2 = s1.clone(); // Creates a completely new copy on the heap.
println!("s1: {}, s2: {}", s1, s2); // Both s1 and s2 are valid.
let s1 = String::from("Event Horizon");
let s2 = s1.clone(); // Creates a completely new copy on the heap.
println!("s1: {}, s2: {}", s1, s2); // Both s1 and s2 are valid.
Performance Note: Cloning involves copying the entire data on the heap, which can be expensive. Use it judiciously.
1.4 Ownership in Functions
Passing a value to a function moves ownership. Returning a value from a function also transfers ownership.
String {
String::from("Andromeda")
}
fn main() {
let nebula = String::from("Orion");
consume_string(nebula); // nebula's ownership is moved.
// println!("{}", nebula); // Error: nebula is no longer valid.
let galaxy = give_ownership(); // Ownership is moved to galaxy.
println!("Received: {}", galaxy);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn consume_string(s: String) {
println!("Consumed: {}", s);
} // s is dropped here
fn give_ownership() -> String {
String::from("Andromeda")
}
fn main() {
let nebula = String::from("Orion");
consume_string(nebula); // nebula's ownership is moved.
// println!("{}", nebula); // Error: nebula is no longer valid.
let galaxy = give_ownership(); // Ownership is moved to galaxy.
println!("Received: {}", galaxy);
}
fn consume_string(s: String) {
println!("Consumed: {}", s);
} // s is dropped here
fn give_ownership() -> String {
String::from("Andromeda")
}
fn main() {
let nebula = String::from("Orion");
consume_string(nebula); // nebula's ownership is moved.
// println!("{}", nebula); // Error: nebula is no longer valid.
let galaxy = give_ownership(); // Ownership is moved to galaxy.
println!("Received: {}", galaxy);
}
Part 2: Borrowing: Access Without Ownership
Borrowing allows you to access data without taking ownership. This is achieved through references.
2.1 Immutable References (&T)
You can create multiple immutable (read-only) references to the same data.
let pulsar = String::from("Neutron Star");
let ref1 = &pulsar; // Immutable borrow
let ref2 = &pulsar; // Another immutable borrow
println!("References: {} and {}", ref1, ref2); // Both ref1 and ref2 are valid
let pulsar = String::from("Neutron Star");
let ref1 = &pulsar; // Immutable borrow
let ref2 = &pulsar; // Another immutable borrow
println!("References: {} and {}", ref1, ref2); // Both ref1 and ref2 are valid
2.2 Mutable References (&mut T)
You can create a mutable (read-write) reference to data. However, there are strict rules:
- Only one mutable reference is allowed at a time for a given piece of data.
- You cannot have both mutable and immutable references to the same data simultaneously.
fn add_fuel(spaceship: &mut String) {
spaceship.push_str(" + Fuel");
}
fn main() {
let mut ship = String::from("Starship");
add_fuel(&mut ship); // Mutable borrow
println!("Upgraded: {}", ship); // Output: Starship + Fuel
}
let mut planet = String::from("Mars");
let r1 = &planet; // OK - immutable borrow
// let r2 = &mut planet; // ERROR! Can't mix mutable and immutable borrows.
println!("{}", r1); // This line is OK because r1 is still in scope
fn add_fuel(spaceship: &mut String) {
spaceship.push_str(" + Fuel");
}
fn main() {
let mut ship = String::from("Starship");
add_fuel(&mut ship); // Mutable borrow
println!("Upgraded: {}", ship); // Output: Starship + Fuel
}
let mut planet = String::from("Mars");
let r1 = &planet; // OK - immutable borrow
// let r2 = &mut planet; // ERROR! Can't mix mutable and immutable borrows.
println!("{}", r1); // This line is OK because r1 is still in scope
2.3 The Borrow Checker
Rust’s compiler includes a “borrow checker” that enforces these borrowing rules at compile time. This prevents data races and other memory safety issues.
fn dangerous_move() {
let mut stars = vec!["Sirius", "Vega"];
let first = &stars[0]; // Immutable borrow
// stars.push("Alpha Centauri"); // ERROR! Mutable borrow while immutable borrow exists.
println!("First star: {}", first);
}
fn dangerous_move() {
let mut stars = vec!["Sirius", "Vega"];
let first = &stars[0]; // Immutable borrow
// stars.push("Alpha Centauri"); // ERROR! Mutable borrow while immutable borrow exists.
println!("First star: {}", first);
}
The compiler will issue an error because you’re trying to modify the vector (stars.push()) while an immutable reference (first) to its elements still exists.
Part 3: Lifetimes — Ensuring Reference Validity
Lifetimes are annotations that specify the relationships between the lifetimes of different references. They ensure that references do not outlive the data they point to, preventing dangling pointers.
3.1 Lifetime Annotations
Lifetime annotations use the ‘ character followed by a name (e.g., 'a). They are placed in function signatures and struct definitions.
<button data-code="fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
Here, 'a indicates that the input string slices x and y, and the returned string slice, all share the same lifetime. This means the returned slice will be valid for as long as both x and y are valid.
3.2 Lifetime Elision
Rust often infers lifetimes automatically through a set of rules called “lifetime elision.” This reduces the need for explicit annotations in many common cases.
3.3 Example: Preventing Dangling References
Lifetimes prevent dangling pointers:
&String {
// let s = String::from("hello");
// &s // s is dropped at the end of this function, leaving a dangling pointer.
// }
// fn main() {
// let reference_to_nothing = dangle(); // Error caught by the compiler!
// println!("Dangling reference: {}", reference_to_nothing);
// }” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// This will cause a compile-time error!
// fn dangle() -> &String {
// let s = String::from("hello");
// &s // s is dropped at the end of this function, leaving a dangling pointer.
// }
// fn main() {
// let reference_to_nothing = dangle(); // Error caught by the compiler!
// println!("Dangling reference: {}", reference_to_nothing);
// }
// This will cause a compile-time error!
// fn dangle() -> &String {
// let s = String::from("hello");
// &s // s is dropped at the end of this function, leaving a dangling pointer.
// }
// fn main() {
// let reference_to_nothing = dangle(); // Error caught by the compiler!
// println!("Dangling reference: {}", reference_to_nothing);
// }
The compiler will catch this error because it knows that the returned reference would outlive the data it points to.
Part 4: Practical Patterns and Common Errors
- Prefer borrowing: Use references whenever possible to avoid unnecessary ownership transfers.
- Return owned values: When creating new data, return owned values.
- Common Errors:
- “use of moved value”: Use
clone()or borrowing. - “cannot borrow as mutable”: Ensure only one mutable borrow at a time.
- “does not live long enough”: Restructure code to satisfy lifetime requirements.
Part 5: Advanced Insights (Brief Overview)
- Copy Trait: Types that implement the
Copytrait (like integers) are copied instead of moved. - Slice Types: Slices (
&[T]) provide borrowed views into contiguous sequences of data.
Self Check: Test Your Understanding
Before moving on to the coding exercise, try answering these questions:
1️. Ownership & Moves:
- What happens when you assign one variable to another in Rust?
- How does Rust prevent use-after-free errors when ownership is moved?
2️. Borrowing & References:
- Can you have multiple mutable references to the same variable at the same time? Why or why not?
- What’s the difference between an immutable reference and a mutable reference?
3️. Lifetimes:
- What do lifetime annotations (
'a) do, and why are they necessary? - How does Rust prevent dangling references?
Practice Exercise: Galactic Database
<button data-code="// Import required module
// though striclty not required in this case
use std::option::Option;
// Define a struct for a SpacePort, holding a list of ships :
// struct is bascically a container that stores data , more on this later
struct SpacePort {
ships: Vec, // Stores names of docked ships
last_arrival: Option, // Tracks the last arriving ship
}
impl SpacePort {
// Creates a new SpacePort instance
fn new() -> Self {
SpacePort {
ships: Vec::new(), // Initialize with an empty list of ships
last_arrival: None, // No ships have arrived yet
}
}
// Registers a new ship by name (borrows the name but takes ownership)
fn register_ship(&mut self, name: &str) {
let owned_name = String::from(name); // Convert &str to owned String
self.ships.push(owned_name.clone()); // Store a copy in the list
self.last_arrival = Some(owned_name); // Track the last arrival
}
// Finds the longest ship name in the list (borrowing, does not take ownership)
fn longest_ship_name(&self) -> Option {
self.ships
.iter() // Iterate over ship names
.max_by_key(|s| s.len()) // Find the longest name
.map(|s| s.as_str()) // Convert &String to &str
}
}
fn main() {
let mut port = SpacePort::new(); // Create a new SpacePort
port.register_ship("Andromeda");
port.register_ship("Galactic Voyager");
port.register_ship("Nebula Runner");
println!("Last Arrival: {:?}", port.last_arrival); // Show last arrival
match port.longest_ship_name() {
Some(name) => println!("Longest Ship Name: {}", name),
None => println!("No ships registered yet."),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Import required module
// though striclty not required in this case
use std::option::Option;
// Define a struct for a SpacePort, holding a list of ships :
// struct is bascically a container that stores data , more on this later
struct SpacePort {
ships: Vec<String>, // Stores names of docked ships
last_arrival: Option<String>, // Tracks the last arriving ship
}
impl SpacePort {
// Creates a new SpacePort instance
fn new() -> Self {
SpacePort {
ships: Vec::new(), // Initialize with an empty list of ships
last_arrival: None, // No ships have arrived yet
}
}
// Registers a new ship by name (borrows the name but takes ownership)
fn register_ship(&mut self, name: &str) {
let owned_name = String::from(name); // Convert &str to owned String
self.ships.push(owned_name.clone()); // Store a copy in the list
self.last_arrival = Some(owned_name); // Track the last arrival
}
// Finds the longest ship name in the list (borrowing, does not take ownership)
fn longest_ship_name(&self) -> Option<&str> {
self.ships
.iter() // Iterate over ship names
.max_by_key(|s| s.len()) // Find the longest name
.map(|s| s.as_str()) // Convert &String to &str
}
}
fn main() {
let mut port = SpacePort::new(); // Create a new SpacePort
port.register_ship("Andromeda");
port.register_ship("Galactic Voyager");
port.register_ship("Nebula Runner");
println!("Last Arrival: {:?}", port.last_arrival); // Show last arrival
match port.longest_ship_name() {
Some(name) => println!("Longest Ship Name: {}", name),
None => println!("No ships registered yet."),
}
}
// Import required module
// though striclty not required in this case
use std::option::Option;
// Define a struct for a SpacePort, holding a list of ships :
// struct is bascically a container that stores data , more on this later
struct SpacePort {
ships: Vec<String>, // Stores names of docked ships
last_arrival: Option<String>, // Tracks the last arriving ship
}
impl SpacePort {
// Creates a new SpacePort instance
fn new() -> Self {
SpacePort {
ships: Vec::new(), // Initialize with an empty list of ships
last_arrival: None, // No ships have arrived yet
}
}
// Registers a new ship by name (borrows the name but takes ownership)
fn register_ship(&mut self, name: &str) {
let owned_name = String::from(name); // Convert &str to owned String
self.ships.push(owned_name.clone()); // Store a copy in the list
self.last_arrival = Some(owned_name); // Track the last arrival
}
// Finds the longest ship name in the list (borrowing, does not take ownership)
fn longest_ship_name(&self) -> Option<&str> {
self.ships
.iter() // Iterate over ship names
.max_by_key(|s| s.len()) // Find the longest name
.map(|s| s.as_str()) // Convert &String to &str
}
}
fn main() {
let mut port = SpacePort::new(); // Create a new SpacePort
port.register_ship("Andromeda");
port.register_ship("Galactic Voyager");
port.register_ship("Nebula Runner");
println!("Last Arrival: {:?}", port.last_arrival); // Show last arrival
match port.longest_ship_name() {
Some(name) => println!("Longest Ship Name: {}", name),
None => println!("No ships registered yet."),
}
}
Key Takeaways
- Ownership: Manages memory safety by ensuring each value has one owner.
- Borrowing: Enables safe data access without ownership transfer
That’s it for this lesson! In the next part, we’ll explore slices ,structs and enums, learning how to model data effectively in Rust.
Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin


