]>
Commit | Line | Data |
---|---|---|
1b1a35ee | 1 | A mutable reference was used in a constant. |
f035d41b XL |
2 | |
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0764 | |
f035d41b XL |
6 | #![feature(const_mut_refs)] |
7 | ||
8 | fn main() { | |
9 | const OH_NO: &'static mut usize = &mut 1; // error! | |
10 | } | |
11 | ``` | |
12 | ||
1b1a35ee XL |
13 | Mutable references (`&mut`) can only be used in constant functions, not statics |
14 | or constants. This limitation exists to prevent the creation of constants that | |
15 | have a mutable reference in their final value. If you had a constant of | |
16 | `&mut i32` type, you could modify the value through that reference, making the | |
17 | constant essentially mutable. | |
18 | ||
19 | While there could be a more fine-grained scheme in the future that allows | |
20 | mutable references if they are not "leaked" to the final value, a more | |
21 | conservative approach was chosen for now. `const fn` do not have this problem, | |
22 | as the borrow checker will prevent the `const fn` from returning new mutable | |
23 | references. | |
24 | ||
f035d41b XL |
25 | Remember: you cannot use a function call inside a constant or static. However, |
26 | you can totally use it in constant functions: | |
27 | ||
28 | ``` | |
f035d41b XL |
29 | #![feature(const_mut_refs)] |
30 | ||
31 | const fn foo(x: usize) -> usize { | |
32 | let mut y = 1; | |
33 | let z = &mut y; | |
34 | *z += x; | |
35 | y | |
36 | } | |
37 | ||
38 | fn main() { | |
39 | const FOO: usize = foo(10); // ok! | |
40 | } | |
41 | ``` |