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!");
r1again. And then try it after making itmut. You can think of those as kind of external and internal mutability. The way you have it now you can modify the string internally, but you cannot modify the variable.&mut smakesr1refer to something mutable, allowing you to do*r1 = some_other_stringat a later point (as well as modifying it in-place withr1.push_str()and others.).mut r1makest1itself mutable, allowing you to dor1 = reference_to_some_other_stringat a later point.