什么是“借入的数据不能存储在其关闭的外部”?意思? [英] What does "borrowed data cannot be stored outside of its closure" mean?

查看:87
本文介绍了什么是“借入的数据不能存储在其关闭的外部”?意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编译以下代码时:

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

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

What does this error mean, and how can I fix my code?

推荐答案

它的确切含义是:借用的数据仅在关闭期间有效。尝试将其存储在闭包之外会使代码暴露于内存不安全中。

It means exactly what it says: that the data you are borrowing only lives for the duration of the closure. Attempting to store it outside of the closure would expose the code to memory unsafety.

之所以会出现这种情况,是因为推断出的闭包参数的生存期与存储在闭包中的生存期无关。 Vec

This arises because the inferred lifetime of the closure's argument has no relation to the lifetimes stored in the Vec.

通常,这不是您遇到的问题,因为某物具有导致发生更多类型推断。在这种情况下,可以将类型添加到 fields 并将其从闭包中删除:

Generally, this isn't a problem you experience because something has caused more type inference to happen. In this case, you can add a type to fields and remove it from the closure:

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

这篇关于什么是“借入的数据不能存储在其关闭的外部”?意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆