“borrowed data cannot be stored outside of its closure”是什么意思?(该问题涉及IT技术)

12

编译以下代码时:

fn main() {
    let mut fields = Vec::new();
    let pusher = &mut |a: &str| {
        fields.push(a);
    };
}

编译器给我以下错误:

error: borrowed data cannot be stored outside of its closure
 --> src/main.rs:4:21
  |
3 |     let pusher = &mut |a: &str| {
  |         ------        --------- ...because it cannot outlive this closure
  |         |
  |         borrowed data cannot be stored into here...
4 |         fields.push(a);
  |                     ^ cannot be stored outside of its closure

在Rust的后续版本中:

error[E0521]: borrowed data escapes outside of closure
 --> src/main.rs:4:9
  |
2 |     let mut fields = Vec::new();
  |         ---------- `fields` declared here, outside of the closure body
3 |     let pusher = &mut |a: &str| {
  |                        - `a` is a reference that is only valid in the closure body
4 |         fields.push(a);
  |         ^^^^^^^^^^^^^^ `a` escapes the closure body here

这个错误的含义是什么,我该如何修复我的代码?

1个回答

11

这句话的意思就是:你所借用的数据只在闭包的持续时间内存在。试图将其存储在闭包之外会使代码暴露于内存不安全的风险。

出现这种情况是因为闭包参数的推断生命周期与存储在 Vec 中的生命周期无关。

通常,你不会遇到这种问题,因为某些原因会导致更多的类型推断发生。在这种情况下,可以给 fields 添加一个类型,并将其从闭包中删除:

let mut fields: Vec<&str> = Vec::new();
let pusher = |a| fields.push(a);

哦,谢谢!我本以为会出现错误提示borrowchk没有足够的信息。 - Valentin Lorentz
@ValentinLorentz,就我所知,我从未见过这种特定的错误,并且这是第一个关于它的SO问题。这可能是一个全新的错误。您可以希望使用您的情况和错误消息提交错误,并表示它没有帮助。 Rust贡献者努力提供有用的错误消息。 - Shepmaster
我花了几个小时误解了“并将其从闭包中删除”的部分。问题不在于你是否厌倦了它,而是你必须将其删除才能使其编译。 - Stein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接