Ownership and Borrowing in Rust: ELI5 edition

Alexander Wichmann Carlsen
2 min readDec 19, 2022

--

Imagine that you have a shed with different tools in it. The shed represents the memory that our program can use. When you want to use a tool, you can take it out of the shed and use it. But while you are using the tool, it is not in the shed anymore. This is like how, when our program uses a piece of data, it takes ownership of that data and is responsible for managing it.

Now, let’s say you have a friend over and they want to use one of your tools. You can let your friend borrow the tool while they use it, but you still own it and is responsible for it. When your friend is done using the tool, they give it back to you and you can put it back in the shed. This is like how we can borrow data in our program — we can let another part of the program use the data, but we are still responsible for managing it.

Here’s an example of how ownership and borrowing might look in using the above analogy:

Ownership

fn main() {
let shovel = String::from("Shovel");
friend(shovel);
}

fn friend(s: String) {
println!("now owns {}", s);
}

In this code, we have a variable shovel which in this example is simply the string representation “shovel”.
We have a function called friend, which represents our friend that wants to own the tool.

If we want to use the shovel again (in main), we cant, as ownership has been transferred, we can prove this by adding a println! after the friend method, then the code will not compile.

This is due to ownership being transferred to the friend (the friend function).

We wanted our friend to borrow the shovel, not own it!. Instead we must pass by reference (borrow the shovel to our friend).

Borrowing

The exact same example, but with borrowing instead

fn main() {
let shovel = String::from("Shovel");
friend(&shovel);
println!("I still own {}", shovel);
}

fn friend(s: &String) {
println!("Borrowed {}", s);
}

--

--

Alexander Wichmann Carlsen
Alexander Wichmann Carlsen

No responses yet