In the Rust language we must mark variables or references that can be changed in memory. The mut
keyword refers to mutable variables.
When deciding what code owns the memory for a variable, mutability is important. It is safe for any code to read memory, but writing to memory can interfere with code correctness elsewhere.
Local variables that are modified more than once must be marked with mut
. Even a simple local integer must have the mut
keyword. This program won't compile.
fn main() { // This variable must be mut x. let x = 10; println!("{}", x); x += 1; println!("{}", x); }error[E0384]: cannot assign twice to immutable variable x ... help: consider making this binding mutable: mut x ... cannot assign twice to immutable variable
Here we add the needed mut
keyword. The program compiles and works as expected, and the variable x can be modified any number of times.
fn main() { // This variable must be mut x. let mut x = 10; println!("{}", x); x += 1; println!("{}", x); }10 11
Suppose we are passing a reference to a struct
—this is efficient, as the struct
does not need to be copied. But we cannot by default modify the struct
in the function we call.
update_features
, but this does not compile. We must have a mutable Bird reference.struct Bird { feathers: Vec<u8> } fn update_feathers(b: &Bird) { // This modifies the Bird, so it must have a mutable reference. b.feathers.push(1); } fn main() { let mut b = Bird{feathers:vec![]}; // Does not compile. update_feathers(&b); println!("Feathers: {}", b.feathers.len()); }error[E0596]: cannot borrow b.feathers as mutable, as it is behind a & reference ... help: consider changing this to be a mutable reference: &mut Bird ... b is a & reference, so the data it refers to cannot be borrowed as mutable
To fix the mutable reference problem, we can use the "ampersand mut
" syntax. This syntax means we want to modify the data pointed to by the reference.
mut
" object anywhere, it is just a keyword in Rust.struct Bird { feathers: Vec<u8> } fn update_feathers(b: &mut Bird) { // This modifies the Bird. b.feathers.push(1); } fn main() { let mut b = Bird{feathers:vec![]}; update_feathers(&mut b); println!("Feathers: {}", b.feathers.len()); }Feathers: 1
We fixed some errors with the "mut
" keyword in Rust in the simplest possible way. Rust tracks parts of code that change data pointed to by references.