]>
Commit | Line | Data |
---|---|---|
ba9703b0 | 1 | A variable used inside an inner function comes from a dynamic environment. |
60c5eb7d XL |
2 | |
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0434 | |
6 | fn foo() { | |
7 | let y = 5; | |
8 | fn bar() -> u32 { | |
9 | y // error: can't capture dynamic environment in a fn item; use the | |
10 | // || { ... } closure form instead. | |
11 | } | |
12 | } | |
13 | ``` | |
14 | ||
ba9703b0 XL |
15 | Inner functions do not have access to their containing environment. To fix this |
16 | error, you can replace the function with a closure: | |
60c5eb7d XL |
17 | |
18 | ``` | |
19 | fn foo() { | |
20 | let y = 5; | |
21 | let bar = || { | |
22 | y | |
23 | }; | |
24 | } | |
25 | ``` | |
26 | ||
ba9703b0 | 27 | Or replace the captured variable with a constant or a static item: |
60c5eb7d XL |
28 | |
29 | ``` | |
30 | fn foo() { | |
31 | static mut X: u32 = 4; | |
32 | const Y: u32 = 5; | |
33 | fn bar() -> u32 { | |
34 | unsafe { | |
35 | X = 3; | |
36 | } | |
37 | Y | |
38 | } | |
39 | } | |
40 | ``` |