Reinitialize or mut?

let mut x = 4;
let y = 4;
x = 5;
let y = 5;

x and y now are 5. what is the most efficient way to reassign values to variables? Using mut or not?

thx

I mean, just do what makes sense. Sometimes you have to use mut, e.g. if it's modified in a loop, and sometimes you have to reassign it because the type is changed.

There's no performance difference between the two methods thanks to the optimizer. At least not in any predictable way.

1 Like

Using mut will change the value of the variable x. Using another let statement declares a completely new variable that just happens to be named y. That's to say, if I have the following code:

struct Foo;
impl Drop for Foo {
    fn drop(&mut self) {
        println!("This object has died");
    }
}

fn main() {
    let value = Foo;
    let value = Foo;
    println!("Hello, World");
}

Will print:

Hello, World
This object has died
This object has died

While swapping out the main code for the following:

fn main() {
    let mut value = Foo;
    value = Foo;
    println!("Hello, World");
}

Will print the following:

This object has died
Hello, World
This object has died

Since in the second example, the object that was originally under value was destroyed as soon as first got its value reassigned. In the first example, the second value just "shadows" the first value, so the second value gets dropped like any other local variable, since it was never removed, just shadowed by the second value.


Playground:
Note that even if the compiler warns that the values go unused, it will never break semantics, and this will always hold true, unless there's some undefined behaviour.

Ok, so performance or memory issue, right?

Interesting. Thx.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.