← All writings // #0001

Rust, ownership, borrowing and lifetime

Rust

It has been three months since I began my journey with Rust. I started by watching a course video on freeCodeCamp, then I continued by building some simple projects and testing out some frameworks to hone my skills in Rust.

Well, yes, Rust has some new concepts that we will talk about in this article and a unique learning curve, which makes it more interesting. However, it is still the same as the other programming languages. You do not have to be scared to learn it.

Now, let’s move to some new concepts that were introduced by Rust.

 

Ownership

Let’s say we have this

let num = 1;
let word = String::from("Hello");

let num2 = num1;
let word2 = word;

println!("{}", num);
println!("{}", word);

If we run this code, Rust will complain in line 8, the word doesn’t own the value anymore. Why is this happening? In line 5, we pass the ownership of the variable to word2.

To illustrate it, imagine you have a brother. At your brother’s birthday, you gave him your favourite toy. This process is equivalent to changing ownership in Rust, like how word passes it to word2. Hence, you won’t be able to play with that toy anymore unless you borrow it, which leads to another concept in Rust.

After reading the code, you might have a question. Why can the variable num still have a value? For the detailed answer, we might have to understand how Rust stores its data in memory, but let's keep that for another day. To make it short, the process that happens in line 4 is copying the data. Unlike variable word that have type String, num has a type of integer, so copying data is cheap.

 

Borrowing

From the story, we know that you can borrow the toy from your brother. So does the variable in Rust. There is a concept called borrowing. Let’s take a look at the code below:

let word = String::from("Hello");
let word2 = &word;
println("{}, {}", word, word2);

We can see in line 2 that instead of giving the ownership, we pass the reference to word2. That’s called borrowing in Rust. You can lend your toy without giving it away forever.

But take note. There are certain rules in Rust related to borrowing:

  • You can have many variables reading the value at the same time.
  • But only one variable can modify it exclusively if they want to change it.

 

Lifetime

Now, imagine if there’s a timer. Rust wants to know, “How long will that toy be around?”

That’s called a lifetime.

fn playground() -> &String {
  let toy = String::from("Hello");
  &toy
}

To illustrate, if you are in a playground that borrows you a toy. You can play with the toy in the playground. However, you cannot take it home.
In Rust, the variable is gone when the function ends. So you cannot give a reference anymore since the data has already disappeared from memory.