在多个闭包之间共享可变向量

时间:2017-04-22 23:09:37

标签: vector rust closures mutable

我正在编写一个程序,使用hlua来调用推送到Vec的Lua代码。问题是,我有多个Lua方法推送到同一个Vec。这是我想要做的非常简化的版本:

let mut vec = Vec::new();
{
    let mut lua = Lua::new();

    // these functions do different things in my actual code
    lua.set("pushA", hlua::function1(|s: String| {
        vec.push(s);
    }));
    lua.set("pushB", hlua::function1(|s: String| {
        vec.push(s);
    }));

    lua.execute::<()>("...");
}

编译器错误:

error[E0499]: cannot borrow `vec` as mutable more than once at a time
  --> src/main.rs:11:42
   |
10 |         lua.set("pushA", hlua::function1(|s: String| { vec.push(s); }));
   |                                          -----------   --- previous borrow occurs due to use of `vec` in closure
   |                                          |
   |                                          first mutable borrow occurs here
11 |         lua.set("pushB", hlua::function1(|s: String| { vec.push(s); }));
   |                                          ^^^^^^^^^^^   --- borrow occurs due to use of `vec` in closure
   |                                          |
   |                                          second mutable borrow occurs here
...
14 |     }
   |     - first borrow ends here

我理解,但我无法找到解决问题的方法,而这种解决方案不会以这种或那种方式发生。我对Rust很新,所以这可能是一个愚蠢的问题。

0 个答案:

没有答案