Learn Rust · 3/14

The Secret Sauce: Ownership and Borrowing

11 min read

Welcome, Rustacean! Get ready to learn about the single most unique feature of Rust, the one that gives it superpowers: Ownership.

Most high-level languages use a "garbage collector" (GC) that periodically cleans up memory you're no longer using. It's helpful, but that cleanup process can pause your application at unpredictable times. Low-level languages like C/C++ give you manual control, but this power comes with great responsibility. It's notoriously easy to make mistakes that lead to bugs and security vulnerabilities.

Rust walks a third path. It manages memory through a system of ownership with a set of rules the compiler checks at compile time. This means you get the performance of manual memory management without the risk of common memory bugs. It might feel a little strange at first, but once it clicks, you'll see it as a powerful ally.


1. The Ownership Rules: Memory Safety Without a Garbage Collector

The Problem: The Chaos of Manual Memory Management

In languages where you manage memory yourself, you're prone to a few classic, hard-to-debug problems:

  • Dangling Pointers: You free some memory, but still hold a pointer to it. Trying to use that pointer later can lead to unpredictable behavior or crashes.
  • Double Free: You accidentally try to free the same memory twice, which can corrupt your memory management system.
  • Memory Leaks: You forget to free memory that you're done with. Your program's memory usage grows and grows until it potentially crashes.

These issues have plagued programmers for decades. So, how does Rust solve this without the runtime performance cost of a garbage collector?

The Solution: The Rules of Ownership 📜

Rust enforces a simple set of rules at compile time that govern how your program manages memory. If you break these rules, your code won't even compile!

The Three Golden Rules:

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped (i.e., the memory is freed).

Let's see this in action.

Scope and Dropping

A scope is the range within a program for which an item is valid. When a variable comes into scope, it's valid. When it goes out of scope, it's no longer valid.

rust
{                      // s is not valid here, it’s not yet declared
    let s = "hello";   // s is valid from this point forward

    // do stuff with s
}                      // this scope is now over, and s is no longer valid

This is simple enough. But things get more interesting when we deal with data on the heap.

The String Type: A Tale of Stack and Heap

To understand ownership well, we need a data type more complex than a simple number. Let's use String, which manages data on the heap.

  • Stack: Fast memory for data with a known, fixed size. Think of it like a stack of plates—last one on, first one off.
  • Heap: Slower memory for data that can grow or has an unknown size at compile time. When you need space on the heap, the memory allocator finds an empty spot and returns a pointer to it.

Simple types like i32, bool, and f64 live entirely on the stack. For String, a pointer to the actual text data, along with its length and capacity, is stored on the stack, while the text content itself is on the heap.

Ownership Transfer: Move vs. Copy

Let's see what happens when we assign one variable to another.

With simple stack-only data, it's a simple copy:

rust
let x = 5;
let y = x; // The value 5 is copied. Both x and y are valid.
println!("x = {}, y = {}", x, y); // This works perfectly fine.

Now, let's try this with a String:

rust
let s1 = String::from("hello");
let s2 = s1; // This is a "move", not a copy!

// The line below will cause a compile-time error!
// println!("s1 = {}", s1); 

What's happening here? 🤔
When we assign s1 to s2, Rust considers s1 to be no longer valid. This is called a move. Ownership of the heap data has been moved from s1 to s2.

Imagine you own a unique, physical book (s1). You can't just magically duplicate it. If you give it to a friend (s2 = s1), they now own it. You no longer have it.

This prevents the "double free" problem. When s2 goes out of scope, it will free the memory. If s1 were still considered valid, it would also try to free the same memory when it went out of scope—a disaster!

If you really want a deep copy of heap data, you must explicitly call the clone() method.

rust
let s1 = String::from("hello");
let s2 = s1.clone(); // This creates a full copy of the heap data.

println!("s1 = {}, s2 = {}", s1, s2); // Now both are valid and independent.

A quick note on the Copy trait: Types like integers are cheap to copy and live on the stack, so they have a special Copy trait. This is why let y = x; is allowed to keep x valid. String does not have the Copy trait.


2. References and Borrowing: Lending Your Data 🤝

The Problem: The Inconvenience of Moving

Moving ownership all the time is safe, but it can be annoying. What if we want a function to use a value but not take ownership of it?

rust
fn main() {
    let s1 = String::from("hello");
    
    // calculate_length takes ownership of s1...
    let (s2, len) = calculate_length(s1); 
    
    println!("The length of '{}' is {}.", s2, len);
}

// ...and has to return it so we can use it again.
fn calculate_length(s: String) -> (String, usize) {
    let length = s.len();
    (s, length)
}

This is a bit clunky. We have to pass the String back out of the function just so we can keep using it. There's a better way!

The Solution: Borrowing with References

Rust lets you create references, which allow you to refer to a value without taking ownership of it. We call this borrowing.

A reference is like a pointer, but with the compiler's guarantee that it will always point to valid data. We use the & symbol to create a reference.

Think of it like lending your book to a friend. They can read it, but you're still the owner, and you expect to get it back. They've borrowed it.

rust
fn main() {
    let s1 = String::from("hello");

    // We pass a reference to s1, not s1 itself.
    let len = calculate_length(&s1); 
    
    // s1 is still valid here!
    println!("The length of '{}' is {}.", s1, len); 
}

// The function takes a reference to a String.
fn calculate_length(s: &String) -> usize {
    s.len()
} // s goes out of scope here, but because it does not own the data,
  // the data it refers to is NOT dropped.

The Two Rules of Borrowing

Borrowing is powerful, but it has two very strict rules that the compiler enforces to prevent data races. A data race occurs when two or more pointers access the same data at the same time, at least one of them is writing, and there's no synchronization.

  1. You can have either one mutable reference (&mut T) OR any number of immutable references (&T) in a particular scope.
  2. References must always be valid.

Rule 1: One Writer OR Many Readers
This is Rust's secret weapon for preventing data races at compile time.

You can have as many immutable references as you want, because they can't change the data.

rust
let s = String::from("hello");

let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);

But if you have a mutable reference, you can't have any other references (mutable or immutable) in that scope.

rust
let mut s = String::from("hello");

let r1 = &s; // immutable borrow
let r2 = &s; // immutable borrow
// let r3 = &mut s; // BIG PROBLEM! Cannot borrow `s` as mutable because it is also borrowed as immutable.
// println!("{}, {}, and {}", r1, r2, r3);

This code won't compile because you can't have a mutable reference while immutable ones exist.

Rule 2: No Dangling References
The compiler also ensures that your references never outlive the data they point to. This prevents dangling pointers.

rust
// This function will not compile!
// fn dangle() -> &String {
//     let s = String::from("hello");
//
//     &s // We return a reference to s...
// } // ...but s goes out of scope and is dropped here! The reference would point to invalid memory.

The borrow checker saves us from ourselves! The only solution here is to return the String directly, transferring ownership.


3. The Slice Type: Referencing Sequences Safely

The Problem: Unsynchronized Data

Imagine we write a function to find the first word in a string. It might return the index where the word ends.

rust
fn first_word_index(s: &String) -> usize {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }
    s.len()
}

This works, but it's brittle. What happens if we use it like this?

rust
let mut s = String::from("hello world");
let word_end_index = first_word_index(&s); // word_end_index is 5

s.clear(); // This empties the String, making it ""

// `word_end_index` still has the value 5, but there's no string data
// associated with it anymore. If we try to use it, we'll get a bug!

Our word_end_index is now completely disconnected from the state of s.

The Solution: Slices 🔪

A slice is a reference to a contiguous sequence of elements in a collection rather than the whole collection. It's a "view" into a part of the data.

A string slice is a reference to a part of a String. Its type is written as &str.

rust
let s = String::from("hello world");

let hello = &s[0..5]; // or &s[..5]
let world = &s[6..11]; // or &s[6..]
let whole_string = &s[..];

Now, let's rewrite our function to return a slice. This is much more robust.

rust
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

An interesting fact: String literals (let s = "hello";) are actually slices! Their type is &'static str, a slice that points directly into the program's binary.

The big win here is safety. When you hold a slice (an immutable reference), the borrow checker ensures you cannot also get a mutable reference to the original String.

rust
let mut s = String::from("hello world");

let word = first_word(&s); // `word` is an immutable borrow.

// s.clear(); // COMPILE ERROR! Cannot borrow `s` as mutable
            // because it is also borrowed as immutable by `word`.

println!("the first word is: {}", word); // The borrow is used here, so it's still active.

The compiler prevents us from invalidating our slice, turning a potential runtime bug into a compile-time error!

Slices also work for other collections like arrays and vectors.

rust
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; // This slice has the type &[i32]

4. Fixing Common Borrow Checker Errors

The borrow checker is your best friend, but it can be a very strict friend. Learning to interpret its messages is a key skill for any Rust developer. Remember, it's not angry at you; it's protecting you from future bugs!

Error 1: "cannot borrow x as mutable because it is also borrowed as immutable"

This happens when you violate the "One Writer OR Many Readers" rule.

rust
let mut data = vec![1, 2, 3];
let first_element = &data[0]; // Immutable borrow starts here

// data.push(4); // ERROR! `data` is borrowed as mutable here.

println!("The first element is: {}", first_element); // Immutable borrow used here

The Fix: Ensure the scopes of your borrows don't overlap. The immutable borrow on first_element lasts until its last use (println!). If you move data.push(4) to after the println!, it will compile, because the immutable borrow is no longer needed.

Error 2: "use of moved value: s1"

You're trying to use a variable after its ownership has been moved.

rust
let s1 = String::from("hello");
let s2 = s1; // `s1` is moved to `s2`.

// println!("{}", s1); // ERROR! `s1` has been moved.

The Fix:

  1. If you needed a copy, use s2 = s1.clone().
  2. If you only needed to read the value, pass a reference (&s1).
  3. If a function took ownership, have it return ownership to you.

Error 3: "returns a reference to data owned by the current function"

This is the classic dangling reference error.

rust
// fn dangle() -> &String {
//     let s = String::from("hello");
//     &s // ERROR! `s` will be dropped, leaving a dangling reference.
// }

The Fix: Return the value itself to transfer ownership to the caller.

rust
fn no_dangle() -> String {
    let s = String::from("hello");
    s // Ownership is moved out.
}

Further Reading

Mastering Ownership is the key to mastering Rust. It's a concept that pays dividends in writing safe, concurrent, and high-performance code.

Challenge

Challenge: In-Place Censoring and Reporting

Your task is to implement a Rust function named censor_and_report that modifies a string in-place to censor a specific word and reports on the modifications.

Function Signature:

rust
fn censor_and_report(text: &mut String, censor_word: &str) -> (usize, Option<usize>)

Requirements:

  1. The function must accept a mutable reference to a String and an immutable string slice representing the word to censor.
  2. It must iterate through the text, find all occurrences of censor_word, and replace each one with asterisks (*). The number of asterisks must match the byte length of censor_word.
  3. The modification must happen in-place. Do not create a new String.
  4. The function must return a tuple containing:
    • The total count of censored occurrences (usize).
    • An Option<usize> that holds the starting byte index of the first occurrence found. If the censor_word is not found, this value should be None.

Expected result

Your code should provide a complete and correct implementation of the censor_and_report function that compiles without errors.

  • The function must adhere to the specified signature: fn censor_and_report(text: &mut String, censor_word: &str) -> (usize, Option<usize>).
  • It must correctly manage borrows to modify the input text in-place.
  • When called with let mut s = String::from("the old fox and the new fox"); and censor_word = "fox", the function should modify s to be "the old *** and the new ***" and return the tuple (2, Some(12)).
  • If the censor_word is not found, the original string should remain unchanged, and the function should return (0, None).
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.