[go: up one dir, main page]

Today I Learned

tags


2023/06/18

By default, a closure seems to live as long as its parent function unless you use the move keyword.

fn unmoved<'a>(arg: &'a str) -> impl Fn() + 'a {
    let f = || println!("unmoved: {}", arg);
    f
}

fn moved<'a>(arg: &'a str) -> impl Fn() + 'a {
    let f = move || println!("moved: {}", arg);
    f
}

fn main() {
    unmoved("a")() // does not compile
    moved("b")() // works fine
}

playground link