使用多个闭包改变相同的外部状态

时间:2017-12-19 17:19:18

标签: rust

我很擅长学习Rust。这是一个浓缩而愚蠢的代码示例,我正在尝试编译:

fn do_something(read: &Fn() -> i32, write: &mut FnMut(i32)) {
    if read() == 10 {
        write(11);
    }
}

fn print_11() {
    let mut val = 10;
    do_something(&|| val, &mut |n| val = n);
    println!("Got {}", val);
}

write关闭可变地借用val,而read关闭可以不可靠地借用它。由于这个原因,编译器会阻止它:

error[E0502]: cannot borrow `val` as mutable because it is also borrowed as immutable
 --> src/main.rs:9:32
  |
9 |     do_something(&|| val, &mut |n| val = n);
  |                   -- ---       ^^^ ---    - immutable borrow ends here
  |                   |  |         |   |
  |                   |  |         |   borrow occurs due to use of `val` in closure
  |                   |  |         mutable borrow occurs here
  |                   |  previous borrow occurs due to use of `val` in closure
  |                   immutable borrow occurs here

error[E0502]: cannot borrow `val` as mutable because it is also borrowed as immutable
 --> src/main.rs:9:32
  |
9 |     do_something(&|| val, &mut |n| val = n);
  |                   -- ---       ^^^ ---    - immutable borrow ends here
  |                   |  |         |   |
  |                   |  |         |   borrow occurs due to use of `val` in closure
  |                   |  |         mutable borrow occurs here
  |                   |  previous borrow occurs due to use of `val` in closure
  |                   immutable borrow occurs here

是否有一种惯用的方法来创建两个可以读/写同一个变量的闭包?这是使用像Rc这样的东西吗?

0 个答案:

没有答案