]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0764.md
Merge commit '97e504549371d7640cf011d266e3c17394fdddac' into sync_cg_clif-2021-12-20
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0764.md
1 A mutable reference was used in a constant.
2
3 Erroneous code example:
4
5 ```compile_fail,E0764
6 #![feature(const_mut_refs)]
7
8 fn main() {
9     const OH_NO: &'static mut usize = &mut 1; // error!
10 }
11 ```
12
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
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 ```
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 ```