0

what is the difference between these two scenario I have the same functionality with 2 different model and it is a bit confusing for me !

//model_1

let mut my_str = String::from("ali");
let str1 = &mut my_str; // defining str1 without "mut"

//model_2

let mut my_str = String::from("ali");
let mut str1 = &mut my_str // defining str1 with "mut"
AzAli
  • 1
  • 3
  • This looks like it might be a duplicate of [What's the difference between placing "mut" before a variable name and after the ":"?](https://stackoverflow.com/questions/28587698/whats-the-difference-between-placing-mut-before-a-variable-name-and-after-the) Do the answers to that question answer your own? – trent Oct 11 '19 at 20:28
  • Also see [Why does Rust allow mutation through a reference field using an immutable binding?](https://stackoverflow.com/questions/50124680/why-does-rust-allow-mutation-through-a-reference-field-using-an-immutable-bindin) which is not about your question specifically, but might help you understand the dual meaning of `mut` better. – trent Oct 11 '19 at 20:30

1 Answers1

0

Let's start with the similarity: neither of them compiles, because you cannot acquire a mutable reference (&mut) of an object that is itself not defined as mut.

As for the correct version, it is the following:

let mut my_str = String::from("ali");
let str2 = &mut my_str;

my_str needs to be defined as mutable if we are to grab a mutable reference to it, so that makes the first line unambiguous.

On the second line, the mut prefix to str2 is only necessary if you are going to modify what reference str2 points to. As long as you are only modifying the content of the string (without changing what string you are modifying) you do not need it.

Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66