Skip to Content
Course content

14: Understanding Ownership

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I spent an entire weekend chasing a "use-after-free" bug in a C++ codebase that only triggered under specific load conditions in our staging environment. The code looked perfectly fine. I spent hours staring at pointers, convinced I was losing my mind, only to realize that a temporary object was being deleted by one thread while another thread was still trying to read a property from it. It was a classic memory corruption nightmare—the kind of bug that makes you want to quit the industry and start a farm. When I first encountered Rust, I was skeptical of the "Borrow Checker" because it felt like the compiler was yelling at me for things I thought I had under control. But then it clicked: the compiler wasn't fighting me; it was preventing that weekend of hell from ever happening again.

Moving the Ownership Torch

In most languages you've used, you don't think about who "owns" a piece of memory. You just create an object, pass it around, and the garbage collector cleans it up eventually. Rust doesn't have a garbage collector, but it also doesn't make you manually free memory. Instead, it uses a system of ownership.

The most important rule is this: each value in Rust has a variable that's called its owner, and there can only be one owner at a time. Look at what happens when we work with a String, which is stored on the heap:

let s1 = String::from("Mentorship");
let s2 = s1;

// println!("{}", s1); // This would cause a compile-time error!

In other languages, s2 = s1 would create two references to the same string. In Rust, this is a "move." Because s1 owned the data, and we assigned it to s2, the ownership moved. s1 is now considered uninitialized. If you try to use s1 after that move, the compiler will stop you dead in your tracks. This prevents "double-free" errors where the program tries to clean up the same memory twice when the variables go out of scope.

Borrowing and the Rules of References

Obviously, moving ownership every time you want to pass a string to a function is a pain. You don't want to give away your data just to let a function read it. This is where borrowing comes in. Instead of transferring ownership, you can pass a reference using the & symbol.

fn calculate_length(s: &String) -> usize {
    s.len()
}

let s1 = String::from("Hello Rust");
let len = calculate_length(&s1); // We lend the string, we don't give it away
println!("The length of '{}' is {}.", s1, len); // s1 is still valid here!

Now, here is where the Borrow Checker gets strict. You can have as many immutable references (&T) as you want, OR exactly one mutable reference (&mut T) at a time. You cannot have both. I'll be honest: this is the steepest part of the Rust learning curve. But think about why. If you have one part of your code mutating a string while another part is reading it, you've got a data race. By enforcing this at compile time, Rust guarantees that your memory is safe without needing a heavy runtime to manage it.




📋 Practical Task

Exercise: Repairing the Message Processor

You are building a simple message processing system. The following code is failing to compile because the developer tried to print a message after it was already "moved" into the processing function. Your task is to modify the code so that the process_message function borrows the string instead of taking ownership, allowing the main function to print the final confirmation.

fn process_message(msg: String) {
    println!("Processing: {}", msg);
}

fn main() {
    let my_msg = String::from("System Update Successful");
    
    process_message(my_msg);
    
    // FIX THIS LINE: The compiler says my_msg has been moved
    println!("Log completed for: {}", my_msg); 
}

Requirements:

  • Modify the process_message function signature to accept a reference.
  • Update the function call in main to pass a reference.
  • Ensure the program compiles and prints both the "Processing" and "Log completed" messages.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.