Definition: Mutability

Mutability is the capability of a variable’s value to be altered in memory.

In Rust, all variables are immutable by default.

This design decision is extremely useful in practice and helps us avoid unintended behavior.

Definition: Mutable reference

If you have a mutable reference to a value, you can have no other references to that value, including immutable reference.

The benefit of having this restriction is that Rust can prevent data races at compile time

The scopes of the immutable references r1 and r2 end after the println! where they are last used, which is before the mutable reference r3 is created. These scopes don’t overlap, so this code is allowed: the compiler can tell that the reference is no longer being used at a point before the end of the scope.

let mut s = String::from("hello");
 
// let r1 = &s; // no problem
//          -- immutable borrow occurs here
// let r2 = &s; // no problem
// let r3 = &mut s; // BIG PROBLEM
//          ^^^^^^ mutable borrow occurs here
 
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{r1} and {r2}");
// Variables r1 and r2 will not be used after this point.
 
let r3 = &mut s; // no problem
println!("{r3}");
Link to original

Interior mutability

For more complex data types, we can only declare mutability on the entire type. All fields are either immutable or mutable.

let mut coord = Coordinate { x: 20, y: 20 };
 
// We can mutate each field because coord is mutable.
coord.x = 12;
coord.y = 91;