Posts

Showing posts with the label ownership

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

What does “borrowed data cannot be stored outside of its closure” mean? 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 Answer 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...