Search⌘ K

Mutable to Immutable

Explore Rust’s borrowing model by understanding how mutable and immutable references work. Learn the rules that govern which references can be used, discover why some programs compile while others don’t, and see how Rust automatically converts mutable references to immutable ones for safety. This lesson helps you grasp key Rust principles for managing data mutability and references.

We'll cover the following...

Does the following program compile?

Rust 1.40.0
fn printme(x: &i32) {
println!("{}", x);
}
fn main() {
printme(&5);
}

It sure does! We only read from the immutable reference, x, and therefore everything is fine. How about this program?

Rust 1.40.0
fn printme(x: &mut i32) {
println!("{}", x);
}
fn main() {
printme(&mut 5);
}

Yes, this is fine as well. We have a mutable reference, x, which allows both reading and writing values. ...