It is not possible to change one enumeration value because it is a reassignment of an immutable variable

I have enums containing variables:

enum Asymmetric {
    One(i32),
    Two(i32, i32),
}

I want to change only one field of an existing enumeration without reassigning the entire enumeration. My code ( playground ):

// Does not compile
fn main() {
    let two = Asymmetric::Two(4, 5);
    let mut vec = vec![two];
    foo(&mut vec[0]);
}

fn foo(baa: &mut Asymmetric) {
    match baa {
        &mut Asymmetric::Two(x0, x1) => {
            x0 = 6;
        }
        _ => {}
    }
}

This results in an error:

error[E0384]: re-assignment of immutable variable `x0`
  --> src/main.rs:16:13
   |
15 |         &mut Asymmetric::Two(x0, x1) => {
   |                              -- first assignment to `x0`
16 |             x0 = 6;
   |             ^^^^^^ re-assignment of immutable variable
+4
source share
1 answer

You must use ref mutin the template to bind a variable reference to a given name. See This Work Code ( Playground ):

fn foo(baa: &mut Asymmetric) {
    match *baa {
        Asymmetric::Two(ref mut x0, _) => {
            *x0 = 6;
        }
        _ => {}
    }
}

Some minor changes that are not related to your error, but which improve the quality of the code:

  • deref ( *) match & &mut
  • _ -,

, if let. , match -case, if let:

fn foo(baa: &mut Asymmetric) {
    if let Asymmetric::Two(ref mut x0, _) = *baa {
        *x0 = 6;
    }
}
+12

Source: https://habr.com/ru/post/1657069/


All Articles