Destructure reference to mut

The following code works.

fn by_ref(&x: &i32) -> i32{
    x + 1
}

fn main() {
    let i = 10;
    let res1 = by_ref(&i);
    let res2 = by_ref(&41);
    println!("{} {}", res1,res2);
}

Above, in the function by_ref, x has been destructured from &x in the function parameter.

If I try to do the same thing with a mutable reference it doesn't work. The following code does not work.

fn modifies(&x: &mut f64) {
    x = 1.0;
}

fn main() {
    let mut res = 0.0;
    modifies(&mut res);
    println!("res is {}", res);
}

Can someone please explain why? Thanks.

& T and &mut T are different types; destructing must match the type.
Also need to make the variable x be mut to assign to it.

&mut mut x: &mut f64

What you expect out is a different question.

It's right there in the error message: you're trying to destructure a &mut T as a &T.

fn modifies(&mut x: &mut f64) {

works.

Thanks for the response.

I am afraid fn modifies(&mut x: &mut f64) doesn't compile. I had tried this out before posting the question.

The previous answer by jonh does compile with warnings. The output is wrong, however. What works is

fn modifies(x: &mut f64) {
    *x = 1.0;
}

Thanks for the response.

Your answer compiles with warnings. The output is wrong, however. What works is

fn modifies(x: &mut f64) {
    *x = 1.0;
}

which was something I knew. Somehow the solution with the destructured parameter seemed prettier.

Could you share the variant which gives wrong output? Maybe there is some misunderstanding.

The solution as suggested by jonh compiles with warnings but gives the wrong output( in the rust playground):

fn modifies(&mut mut x: &mut f64) {
    x = 1.0;
}

fn main() {
    let mut res = 0.0;
    modifies(&mut res);
    println!("res is {}", res);
}

Destructuring moves out of the target, which requires the Copy trait to be implemented in this case, since you can't move out of a borrow. So &mut x: &mut i32 gets you, essentially let mut x: i32 = *x;, which is why it doesn't work as expected - you're making a local copy and modifying it.

3 Likes

Got most of what you were saying( am a beginner ). I guess that's it. Thanks.

Oops! Turns out that the compiler error was just off the bottom of my screen; I saw the warnings I expected and so didn't notice. Sorry about that!

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