“借用的数据不能存储在其封闭之外”是什么意思?

2023-11-22

编译以下代码时:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“借用的数据不能存储在其封闭之外”是什么意思? 的相关文章

随机推荐