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?

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.

The only action that Option 2 actually prevents is moving the Car value out, and you can often still do that with std::mem::replace().

I recommend only using Option 2 in cases where it saves you from writing &mut many times later, e.g.

let car2 = &mut Car { color: "blue" };
drive(car2);
park(car2);
wash(car2);

Otherwise, it is a complication which is unidiomatic and brings no real benefit.

4 Likes

That is a funny question. As option two is an indirection, I would have never actually considered it. And from the reply of @kpreid there seems to be no serious reasons for option 2.

1 Like