rustreference

Why can a mutable reference variable be mutated-through even when it itself is not declared mut?


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!");

Solution

  • 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: