I have the following code in Rust:
fn main() {
let global = vec!(1, 2, 3);
fn fn_a() {
println!("{:?}", global);
fn_b();
};
fn fn_b() {
println!("{:?}", global);
fn_a();
};
println!("Done.");
}
This does not compile because code in fn
cannot capture global
, and code in fn_b
cannot capture fn_a
.
I got the following error:
error[E0434]: can't capture dynamic environment in a fn item
--> src/main.rs:193:24
|
193 | println!("{}", global);
| ^^^^^^
|
= help: use the `|| { ... }` closure form instead
error[E0434]: can't capture dynamic environment in a fn item
--> src/main.rs:198:24
|
198 | println!("{}", global);
| ^^^^^^
|
= help: use the `|| { ... }` closure form instead
error: aborting due to 2 previous errors
(rustc --explain E0434)
So I changed to this:
fn main() {
let global = vec!(1, 2, 3);
let closure_a = || {
println!("{:?}", global);
closure_b();
};
let closure_b = || {
println!("{:?}", global);
closure_a();
};
println!("Done.");
}
but still got an error:
error[E0425]: cannot find function `closure_b` in this scope
--> src/main.rs:195:9
|
195 | closure_b();
| ^^^^^^^^^ not found in this scope
error: aborting due to previous error
I guess this is because that the closure's scope begins from the line it is declared.
Is there a method to write a function/closure to call another function/closure which captures a global variable?