Why does the order matter in closures?

Viewed 64

In rust, order of the functions do not matter unlike C or C++ where main function should be at the end. But it is not the same for closures and I wonder why

For example, this code compiles:

fn main(){
    println!("{}", add_up(1));
}
fn add_up(x: i32) -> i32{
    x + y
}
const y:i32 = 1;

and this code does not compile:

fn main(){
    let add_up = |x:i32| x + y;
    let y = 1;
    println!("{}", add_up(1));
}

I know in the first one y is a global variable and that is not a fair comparison but this is the example I can think of at the moment. The main point is, generally order does not matter in rust (where is main located or where is add_up located) but not the same for closures. Why?

1 Answers

The difference between a local variable (which can be captured by a closure) and a constant or static is that the latter don't have "scope", they are available before the program starts and last for as long as the program. A variable, on the other hand, has a clear scope - a place where it's introduced and a place where it's destructed, and attempt to use it outside that region cannot work.

For example, if it were allowed to capture variables that are not yet created might result in non-sensical code like this:

let c = || x;
println!("{}", c());  // what does this print?
let x = some_function_that_takes_user_input();
let x = x + 1;
{
    let x = 100;
}

A static or a const, on the other hand, doesn't have this issue because it's not created at any time, it always exists for as long as the program.

Related