Function set variable declared outside

This code doesn't work, so I'm guessing Rust does not allow a nested function to modify variables declared outside the function, but that would be in its scope in other programming languages. Is that correct?

fn main() {
    let a;
    
    fn inner() {
        a = String::from("test");
    }
    
    inner();
    
    println!("{}", a);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0434]: can't capture dynamic environment in a fn item
 --> src/main.rs:5:9
  |
5 |         a = String::from("test");
  |         ^
  |
  = help: use the `|| { ... }` closure form instead

error[E0282]: type annotations needed
 --> src/main.rs:2:9
  |
2 |     let a;
  |         ^ consider giving `a` a type

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0282, E0434.
For more information about an error, try `rustc --explain E0282`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

Indeed, fn items are always guaranteed to be plain old raw functions, which do not capture state.

The solution is right there in the error message:

help: use the `|| { ... }` closure form instead

(playground)

1 Like

And now I know about closures in Rust ... Thanks @H2CO3!