0
  1. I don't understand why let mut first = in this situation is not good enough for the rust compiler to allow first to be mutable and change first.value
  2. Is this some strange behavior because its contained inside a Box?
  3. What does mut on the right side do that the left mut doesn't?

rustc --explain E0594 doesn't really explain much in this case.

#![allow(unused)]
fn main() {
    let mut all_my_data = Vec::new();
    
    all_my_data.push(Box::new(
        Data::new("Hello World!"),
        ),
    );
    all_my_data.push(Box::new(
        Data::new("This is the end of the World!"),
        ),
    );
    all_my_data.push(Box::new(
        Data::new("Goodbye!"),
        ),
    );
    
    let mut first = &all_my_data[0]; // This errors out
    //let mut first = &mut all_my_data[0]; // This works
    first.value = String::from("Hello New World!");
    println!("First: {:?}", first);
    let second = &all_my_data[1];
    println!("Second: {:?}", second);
    let third = &all_my_data[2];
    println!("Third: {:?}", third);
}

#[derive(Debug)]
struct Data {
    value: String,
}

impl Data {
    pub fn new(value: &str) -> Data {
        Data {
            value: value.to_string()
        }
    }
}
error[E0594]: cannot assign to `first.value`, which is behind a `&` reference
  --> src/main.rs:20:5
   |
18 |     let mut first = &all_my_data[0]; // This errors out
   |                     --------------- help: consider changing this to be a mutable reference: `&mut all_my_data[0]`
19 |     //let mut first = &mut all_my_data[0];
20 |     first.value = String::from("Hello New World!");
   |     ^^^^^^^^^^^ `first` is a `&` reference, so the data it refers to cannot be written

For more information about this error, try `rustc --explain E0594`.
error: could not compile `playground` due to previous error

Playground

David
  • 692
  • 8
  • 21
  • In short: `let mut foo` vs `let foo` is more of the lint, but `&foo` and `&mut foo` have entirely different semantics. – Cerberus Jun 22 '22 at 04:39
  • Yes, this makes a lot more sense now. Would it be reasonable to say the error message should say ```cannot assign to `first.value`, which is behind an immutable `&` reference``` instead? I guess Rust always implies immutable in most cases unlike other languages. – David Jun 22 '22 at 05:18
  • `&` references are shared by definition, and shared values are immutable by default. That's just what's the semantics of language are, it'd be probably redundant to say this explicitly in the error message. Although I agree that this might raise the learning curve. – Cerberus Jun 22 '22 at 05:33

0 Answers0