The following code does not compile.
fn main() { let foo = bar(8); println!("Trying `foo` with 4: {:d}", foo(4)); println!("Trying `foo` with 8: {:d}", foo(8)); println!("Trying `foo` with 13: {:d}", foo(13)); } // fn bar(x: int) -> (|int| -> int) { |n: int| -> int { if n < x { return n } x } } The error is as following.
11:32 error: explicit lifetime bound required .../hello/src/main.rs:11 fn bar(x: int) -> (|int| -> int) { ^~~~~~~~~~~~ I am passing the integer argument to bar by value. Why does Rust care about the lifetime of an integer passed by value? What is the correct way of writing such a function that returns a closure? Thanks.
EDIT
I found the following in the manual. In the simplest and least-expensive form (analogous to a || { } expression), the lambda expression captures its environment by reference, effectively borrowing pointers to all outer variables mentioned inside the function. Alternately, the compiler may infer that a lambda expression should copy or move values (depending on their type.) from the environment into the lambda expression's captured environment.
Is there a further specification of how the compiler infers whether to capture the outer variables by reference, copy them or move them? What are the evaluation criteria, and what is their order of application? Is this documented (short of reading the compiler's code)?