是否可以修改正在进行模式匹配的值?

时间:2018-09-17 15:35:55

标签: rust

在下面的程序中,我尝试创建一个change函数,该函数可变地修改数据类型的构造函数:

enum Typ {
    Foo { x: u32 },
    Bar { x: u32 },
}
use Typ::*;

fn change(val: &mut Typ) {
    match val {
        &mut Foo { ref mut x } => *val = Bar { x: *x },
        &mut Bar { ref mut x } => *val = Foo { x: *x },
    }
}

fn main() {
    let mut val = Foo { x: 1 };
    change(&mut val);
    println!("Hello, world!");
}

那行不通:

error[E0506]: cannot assign to `*val` because it is borrowed
 --> src/main.rs:9:35
  |
9 |         &mut Foo { ref mut x } => *val = Bar { x: *x },
  |                    ---------      ^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `*val` occurs here
  |                    |
  |                    borrow of `*val` occurs here

error[E0506]: cannot assign to `*val` because it is borrowed
  --> src/main.rs:10:35
   |
10 |         &mut Bar { ref mut x } => *val = Foo { x: *x },
   |                    ---------      ^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `*val` occurs here
   |                    |
   |                    borrow of `*val` occurs here

是否可以在其模式匹配子句中修改某些内容?

0 个答案:

没有答案