...

/

Puzzle 18: Explanation

Puzzle 18: Explanation

Let’s learn how mutables and immutables work in Rust.

We'll cover the following...

Test it out

Hit “Run” to see the code’s output.

Press + to interact
fn main() {
let life_the_universe = &mut 41;
*life_the_universe += 1;
println!("Life, the Universe and Everything: {}", life_the_universe);
}

Explanation

The surprising part of this teaser is that the life_the_universe variable is immutable, yet we’re able to change its contents. To understand how this is possible, let’s look at the following illustration:

Notice there are a few unusual things going on here:

  • We can declare a reference to a literal. When we do, Rust creates a temporary area of memory containing the desired value. Because the literal is mutable, we can change it.

  • The life_the_universe reference itself remains immutable. Once we define the reference, it points to the same ...