No warning when mutating a reference to temporary

Hi,

I believe the compiler should warn me that I am trying to modify a reference to a temporary clone

It’s temporary lifetime extension.

struct A {
    i: i32,
}

impl A {
    fn get_i(&self) -> i32 {
        self.i
    }
}


fn main() {
    let a = A{i:1};
    let i = &mut a.get_i();  // Takes mutable reference to copy of a.i, extends lifetime to lifetime of i
    *i = 2; // Modifies the copy, not a.i
 
    println!("i = {}", a.i);
}

OK, I feel like mutating such reference should generate a warning. It could prevent bugs, as I don't think mutating a temporary copy is usually the intention.

Then this could be something for clippy?

1 Like

This probably should generate an "unused value" warning, since you mutate the value and don't use the new value. However, it's very hard to detect.

This actually does what you seem to want to do. Notice that if you remove the mut declaration before a the compiler will warn you. It doesn't warn you in your case because there's nothing to warn about (strictly, since no unwanted mutation is going on) .

Wow, I think you may have just shown me why I was scratching my head over a weird bug for a week.

I had a function that added items to a vector and then returned the vector. Immediately prior to the return a println! showed the vector was changed. Immediately back at the call site a `println!' shows the vector was empty.

I can't show my code that demonstrated that but it was a symptom that sounds like what is described here. A temporary being updated but not the real thing.

Not knowing were the problem was I rearranged a lot of code till it went away?

Perhaps some warning may have helped.

I've made that mistake myself. Fortunately, it was only hard to find the first 6 times. +1 for a warning.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.