[rust-dev] Why the difference between functions and closures?

David Bruant bruant.d at gmail.com
Fri Jul 13 13:14:05 PDT 2012


Le 13/07/2012 21:42, Patrick Walton a écrit :
> On 7/13/12 12:38 PM, David Bruant wrote:
>> I can't help but asking why can't named function close over their
>> environment?
>> In the case above, I see no harm in allowing the 'bar' function to
>> access 'foo'.
>
> Because named functions are always in scope (they're always mutually
> recursive), while locals are not. For example, these two are equivalent:
> fn f() {
>   g();
>   fn g() { ... }
> }
>
> fn f() {
>   fn g() { ... }
>   g();
> }
> But if we allowed items to close over variables, then that wouldn't be
> the case anymore. This cannot be allowed:
>
> fn f() {
>   g();
>   let x = ...;
>   fn g() { ... use x ... }
> }
>
> Because x has not yet been initialized.
Tell me if I'm wrong, but it seems that a use-before-init can be
detected statically at compile time. It wouldn't be the case for
JavaScript, but I think it's feasible in Rust.
Unless I'm missing something, named function could close over variables
and the compiler could throw an error when a named function is being
used in a use-before-init scenario.

David


More information about the Rust-dev mailing list