I have recently started learning Rust from The Book. While learning about ownership, I came up with following piece of code:
let mut s = String::from("hello");
let r1 = &mut s;
Here it confused me. Why are we not using mut
keyword before r1
too?
What if we use mut
keyword? What will it signify?
Because I am still able to modify content with:
r1.push_str(" World!");
A newcomer to Rust might stumble upon what could be considered a slightly unfortunate choice of words. Rust uses mut
is several situations, and they are not the same:
&T
), or "this is a mutable reference" (&mut T
). The choice of words is not exactly precise, and it does not help that the word mut
even appears in the syntax. What we actually mean is "this is a shared reference" (&T
), or "this is an exclusive reference" (&mut T
). The confusion only becomes worse when the objects behind what we call "immutable references" are actually mutable (but let's not get into interior mutability here)...&mut T
as "exclusive reference", not "mutable reference".let mut foo: Foo = ...
declares that foo
itself can change, while a let foo: Foo = ...
says that foo
itself can't change (but the value foo
refers to can). This is basically bookkeeping within the syntax, in order to signal intend by the programmer; it does not reflect what either Foo
or foo
can actually do.