是否有任何方法可以缓解或变通在循环中使用的闭包中可变地捕获环境?

时间:2018-07-28 16:36:12

标签: rust

check_vec()闭包捕获对values向量的可变引用。编译器不够聪明,无法理解values.push(0xbeef)调用是安全的。我曾尝试使用NLL功能标记进行编译,但这也无济于事。

fn main() {
    let mut values = Vec::with_capacity(16);

    let mut check_vec = || {
        if values.len() < 16 {
            values.push(0xdead);
        }
    };

    for _ in 0..32 {
        check_vec();
        values.push(0xbeef);
    }

    check_vec();
}

playground

error[E0499]: cannot borrow `values` as mutable more than once at a time
  --> src/main.rs:12:9
   |
4  |     let mut check_vec = || {
   |                         -- first mutable borrow occurs here
5  |         if values.len() < 16 {
   |            ------ previous borrow occurs due to use of `values` in closure
...
12 |         values.push(0xbeef);
   |         ^^^^^^ second mutable borrow occurs here
...
16 | }
   | - first borrow ends here

是否有任何方法可以减轻或解决此限制?

0 个答案:

没有答案