Lifetimes in Closures

Common Pitfalls and Solutions

Fix Rust closure lifetime errors by ensuring captured references outlive the closure or by moving ownership into the closure.

Lifetimes in closures fail when the closure captures a reference that outlives the data it points to, requiring explicit lifetime annotations or ownership changes. You must ensure the closure's lifetime parameter matches the shortest lifetime of any captured reference or move the data into the closure.

fn main() {
    let data = String::from("hello");
    let closure = || println!("{}", data); // Moves 'data' into closure
    closure();
}

If you must borrow, annotate the closure with a lifetime parameter that matches the borrowed data's scope:

fn make_closure<'a>(input: &'a str) -> impl Fn() + 'a {
    move || println!("{}", input)
}

The compiler infers lifetimes automatically when possible, but explicit annotations resolve ambiguity when capturing references across function boundaries.