]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0764.md
Merge commit '953f024793dab92745fee9cd2c4dee6a60451771' into clippyup
[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_fn)]
7 #![feature(const_mut_refs)]
8
9 fn main() {
10     const OH_NO: &'static mut usize = &mut 1; // error!
11 }
12 ```
13
14 Mutable references (`&mut`) can only be used in constant functions, not statics
15 or constants. This limitation exists to prevent the creation of constants that
16 have a mutable reference in their final value. If you had a constant of
17 `&mut i32` type, you could modify the value through that reference, making the
18 constant essentially mutable.
19
20 While there could be a more fine-grained scheme in the future that allows
21 mutable references if they are not "leaked" to the final value, a more
22 conservative approach was chosen for now. `const fn` do not have this problem,
23 as the borrow checker will prevent the `const fn` from returning new mutable
24 references.
25
26 Remember: you cannot use a function call inside a constant or static. However,
27 you can totally use it in constant functions:
28
29 ```
30 #![feature(const_fn)]
31 #![feature(const_mut_refs)]
32
33 const fn foo(x: usize) -> usize {
34     let mut y = 1;
35     let z = &mut y;
36     *z += x;
37     y
38 }
39
40 fn main() {
41     const FOO: usize = foo(10); // ok!
42 }
43 ```