The Rust Programming Language — References and Borrows — Mutable References
Get some mutable references and understand the borrow checker errors!
4 min readOct 22, 2023
We’ve seen that we can create mutable variables which allow you to modify the variables. Have a look at the below code snippet:
fn main() {
let mut years: Vec<i32> = vec![2001, 2002, 2003, 2004];
let mutable_years: &mut Vec<i32> = &mut years;
}
Observations:
mut years
means you are able to modify theyears
variable by adding or removing the elements from the vector.&mut Vec<i32>
means its a mutable reference. It means that I want to give the reference to thatvec![]
and also be able to mutate thatvec![]
. Normal references, i.e.&Vec<i32>
are like look but don’t touch. You can borrow the references but you can’t mutate them.
Mutable references stretch the metaphor for normal references a little bit. It’s like when the parent function lends years
reference to you, it expects that there can be certain modifications done on the years
. It is not an immutable borrow. For e.g. the .clear()
method on a vector is a great example of mutable reference. .clear()
is going to get certain elevated levels of permissions on the years
variable. It certainly cannot de-allocate…