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