File tree 5 files changed +42
-15
lines changed
compiler/rustc_error_codes/src/error_codes
5 files changed +42
-15
lines changed Original file line number Diff line number Diff line change 1
- A constant item was initialized with something that is not a constant
2
- expression.
1
+ A non-` const ` function was called in a ` const ` context.
3
2
4
3
Erroneous code example:
5
4
@@ -8,26 +7,20 @@ fn create_some() -> Option<u8> {
8
7
Some(1)
9
8
}
10
9
11
- const FOO: Option<u8> = create_some(); // error!
10
+ // error: cannot call non-const fn `create_some` in constants
11
+ const FOO: Option<u8> = create_some();
12
12
```
13
13
14
- The only functions that can be called in static or constant expressions are
15
- ` const ` functions, and struct/enum constructors .
14
+ All functions used in a ` const ` context (constant or static expression) must
15
+ be marked ` const ` .
16
16
17
17
To fix this error, you can declare ` create_some ` as a constant function:
18
18
19
19
```
20
- const fn create_some() -> Option<u8> { // declared as a const function
20
+ // declared as a `const` function:
21
+ const fn create_some() -> Option<u8> {
21
22
Some(1)
22
23
}
23
24
24
- const FOO: Option<u8> = create_some(); // ok!
25
-
26
- // These are also working:
27
- struct Bar {
28
- x: u8,
29
- }
30
-
31
- const OTHER_FOO: Option<u8> = Some(1);
32
- const BAR: Bar = Bar {x: 1};
25
+ const FOO: Option<u8> = create_some(); // no error!
33
26
```
Original file line number Diff line number Diff line change
1
+ static X : i32 = 42 ;
2
+ const Y : i32 = X ; //~ ERROR constants cannot refer to statics [E0013]
3
+
4
+ fn main ( ) { }
Original file line number Diff line number Diff line change
1
+ error[E0013]: constants cannot refer to statics
2
+ --> $DIR/E0013.rs:2:16
3
+ |
4
+ LL | const Y: i32 = X;
5
+ | ^
6
+ |
7
+ = help: consider extracting the value of the `static` to a `const`, and referring to that
8
+
9
+ error: aborting due to previous error
10
+
11
+ For more information about this error, try `rustc --explain E0013`.
Original file line number Diff line number Diff line change
1
+ fn create_some ( ) -> Option < u8 > {
2
+ Some ( 1 )
3
+ }
4
+
5
+ const FOO : Option < u8 > = create_some ( ) ;
6
+ //~^ ERROR cannot call non-const fn `create_some` in constants [E0015]
7
+
8
+ fn main ( ) { }
Original file line number Diff line number Diff line change
1
+ error[E0015]: cannot call non-const fn `create_some` in constants
2
+ --> $DIR/E0015.rs:5:25
3
+ |
4
+ LL | const FOO: Option<u8> = create_some();
5
+ | ^^^^^^^^^^^^^
6
+ |
7
+ = note: calls in constants are limited to constant functions, tuple structs and tuple variants
8
+
9
+ error: aborting due to previous error
10
+
11
+ For more information about this error, try `rustc --explain E0015`.
You can’t perform that action at this time.
0 commit comments