Search⌘ K
AI Features

Puzzle 18: Explanation

Learn how Rust enforces safety with immutable references that can access mutable data through dereferencing. Understand borrowing rules, mutability, and how variables and references interact to maintain safe and efficient code. This lesson clarifies mutable access to data via immutable pointers and the constraints enforced by Rust's compiler.

We'll cover the following...

Test it out

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

C++
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 ...