How can I destruct a mutable reference?

I know I can use derefence for a mutable reference variable to get non-reference type and I also know I can use &x to destruct a immutable reference.


fn test_destruct(&x: &i32) {
     // The type of x is i32
    println!("x = {}", x);
}

fn test_deref(x: &mut i32) {
     // The type of *x is i32
    println!("x = {}", *x);
}

fn test_desm(&mut x: &mut i32) {
    // It is wrong...
    // how can i destruct a mutable reference.
}

It seems to work, what’s your problem?

I think @eadren wants to mutate x.

If you add x = 20 to test_desm body, it goes wrong.

You can do:

fn test_desm(&mut mut x: &mut i32) {
    x = 10;
}

But the “original” i32 won’t be affected, I don’t know if that’s what you want.

1 Like

I guess it is not what I want.

When you destructure any reference, you are essentially copying the value out of it. This is not a problem with shared references, since the value isn’t mutated anyway, but if you want to operate on the value that resides behind the unique reference, you must always work through that reference.

3 Likes
struct Point { x: i32, y: i32 }

fn clear (
    &mut Point { ref mut x, ref mut y }: &mut Point,
)
{
    *x = 0;
    *y = 0;
}
1 Like
struct Point { x: i32, y: i32 }

fn clear (
  Point { x, y }: &mut Point,
)
{
  *x = 0;
  *y = 0;
}
1 Like

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