"borrowed data cannot be stored outside of its closure" 是什么意思?

What does "borrowed data cannot be stored outside of its closure" mean?

编译以下代码时:

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

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

这就是它所说的意思:您借用的数据仅在关闭期间有效。尝试将其存储在闭包之外会使代码暴露于内存不安全。

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

一般来说,这不是您遇到的问题,因为某些事情 导致了更多类型推断的发生。在这种情况下,您可以将类型添加到 fields 并将其从闭包中删除:

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