- I don't understand why
let mut first =
in this situation is not good enough for the rust compiler to allowfirst
to be mutable and changefirst.value
- Is this some strange behavior because its contained inside a
Box
? - What does
mut
on the right side do that the leftmut
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