A mutable object permits its contents to change after creation. In Rust, mutability is explicit: declare a variable with `mut` before reassigning it or changing data through a mutable reference. This small annotation gives the compiler information it can use to check code. section 2.3.2
Changing an artwork through a mutable reference
An artwork can track views when `admire_art` accepts `&mut Artwork` and increments `view_count`. The owning variable must also be mutable: `let mut art1 = Artwork { view_count: 0, name: "".to_string() };`. Each call temporarily borrows the artwork mutably; after the function returns, that reference is dropped before the next call. section 2.3.2
Mutability also changes how growing strings are implemented. An owned Rust `String` stores character data in a growable heap buffer with a length and capacity. Appending usually extends that buffer; reallocation and copying occur only when the new length exceeds capacity. Preallocating capacity can avoid additional allocation while building a large string. section 2.4.1
Listing 2.11 Incrementing a view counter on an artwork using mutable references
struct Artwork {
view_count: i32,
name: String,
}
fn admire_art(art: &mut Artwork) { #1
println!("{} people have seen {} today!",
art.view_count, art.name);
art.view_count += 1; #2
}
fn main() {
let mut art1 = Artwork {
view_count: 0, name: "".to_string() }; #3
admire_art(&mut art1); #4
admire_art(&mut art1);
}
Shows a mutable artwork variable, a mutable reference, and an in-place view-counter update. section 2.3.2
Listing 2.18 Preallocating strings to aid performance
fn main() {
let mut x = String::with_capacity(10_000_000); #1
for i in 0..10_000_000 {
x.push('.');
}
println!("{}", x.len());
}
Shows preallocating a mutable String before repeatedly appending characters. section 2.4.1



