lotsoftools

Understanding Rust Error E0521: Borrowed Data Escapes Outside of Closure

Overview

Rust error E0521 occurs when borrowed data escapes outside the closure. This error usually happens when a type annotation of a closure includes a lifetime that causes the data to persist beyond the scope of the closure.

Erroneous Code Example

Consider the following erroneous code example:

#![allow(unused)]
fn main() {
let mut list: Vec<&str> = Vec::new();

let _add = |el: &str| {
    list.push(el); // error: `el` escapes the closure body here
};
}

Explanation

In the erroneous code example, the variable `el` of type `&str` is defined as a parameter of the closure `_add`. When the closure attempts to push `el` into the `list`, the Rust compiler emits error E0521 because the borrowed data (`el`) escapes the closure body.

Solution

To fix error E0521, remove the type annotation of the closure parameter and allow the Rust compiler to infer lifetimes automatically:

#![allow(unused)]
fn main() {
let mut list: Vec<&str> = Vec::new();

let _add = |el| {
    list.push(el);
};
}

Additional Resources

For more details on Rust closure type inference and lifetime elision, consult the following documentation:

1. Closure type inference and annotation: https://doc.rust-lang.org/book/ch13-01-closures.html 2. Lifetime elision: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html

Recommended Reading