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

﹥>﹥吖頭↗ 提交于 2019-12-10 17:39:04

问题


When compiling the following code:

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

The compiler gives me the following error:

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?


回答1:


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.

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

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);


来源:https://stackoverflow.com/questions/51118023/what-does-borrowed-data-cannot-be-stored-outside-of-its-closure-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!