在 FnMut 闭包中改变由值捕获的 upvar

Mutating an upvar captured by value in a FnMut closure

我正在尝试创建一个简单的程序,其中包含一个逐渐清空自身的集合的闭包:

fn main() {
    let vector = vec![1, 2, 3];

    let mut allow_once = move |i: &i32| -> bool {
        if let Some(index) = vector.position_elem(i) {
            vector.remove(index);
            return true
        }
        false
    };

    for e in &[1, 2, 3, 1, 2, 3] {
        let is_in = if allow_once(e) { "is" } else { "is not" };
        println!("{} {} allowed", e, is_in);
    }
}

这似乎是犹太洁食(对我来说),但 rustc 抱怨(每晚):

<anon>:6:13: 6:19 error: cannot borrow captured outer variable in an `FnMut` closure as mutable
<anon>:6             vector.remove(index);
                     ^~~~~~

我预计问题可能与脱糖有关。也就是说,虽然实现从不违反别名 XOR 突变原则,但也许 desguaring 使得 rustc 没有意识到它。

因此:

  1. 这是临时的 limitation/bug 还是固有的?
  2. 如何尽可能高效地创建具有可变环境的闭包?

注意:通过引用捕获不是一个选项,我希望能够移动闭包。

其实这个问题很容易解决。只需将 mut 限定符添加到 vector:

fn main() {
    let mut vector = vec![1, 2, 3];

    let mut allow_once = move |i: &i32| -> bool {
        if let Some(index) = vector.position_elem(i) {
            vector.remove(index);
            true
        } else { false }
    };

    for e in &[1, 2, 3, 1, 2, 3] {
        let is_in = if allow_once(e) { "is" } else { "is not" };
        println!("{} {} allowed", e, is_in);
    }
}

(工作代码here

它的可变性规则一如既往 - 为了改变某些东西,它必须在某处有 mut,无论是在它的变量声明中还是在它的类型中(&mut)。