Given that I want to create a local variable which I will only change its inner properties, should I prefer mutable reference over mutable binding?
Take the following code as reference:
#[derive(Debug)]
struct Car {
color: &'static str,
}
fn main() {
// Option 1: using mutable binding
let mut car1 = Car { color: "blue" };
car1.color = "red";
println!("(option 1): My car is {car1:?}");
// Option 2: using mutable reference:
let car2 = &mut Car { color: "blue" };
car2.color = "green";
println!("(option 2): My car is {car2:?}");
}
As you can see, it is possible to achieve the same with the two different approaches. To me, it seems better to use mutable reference (option 2) to make the code more restrict, but I am not sure, because I didn't find any resource/discussion about that. In general, the discussions focus only on the difference between the two approaches.
3 posts - 3 participants
Read full topic
🏷️ rust_feed