doc/test: add UI test and reword docs for E0013 and E0015

This commit is contained in:
Ezra Shaw 2023-01-07 18:37:40 +13:00
parent 09382db78b
commit ae61c250cd
No known key found for this signature in database
GPG Key ID: 17CD5C2ADAE0D344
5 changed files with 42 additions and 15 deletions

View File

@ -1,5 +1,4 @@
A constant item was initialized with something that is not a constant
expression.
A non-`const` function was called in a `const` context.
Erroneous code example:
@ -8,26 +7,20 @@ fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some(); // error!
// error: cannot call non-const fn `create_some` in constants
const FOO: Option<u8> = create_some();
```
The only functions that can be called in static or constant expressions are
`const` functions, and struct/enum constructors.
All functions used in a `const` context (constant or static expression) must
be marked `const`.
To fix this error, you can declare `create_some` as a constant function:
```
const fn create_some() -> Option<u8> { // declared as a const function
// declared as a `const` function:
const fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some(); // ok!
// These are also working:
struct Bar {
x: u8,
}
const OTHER_FOO: Option<u8> = Some(1);
const BAR: Bar = Bar {x: 1};
const FOO: Option<u8> = create_some(); // no error!
```

View File

@ -0,0 +1,4 @@
static X: i32 = 42;
const Y: i32 = X; //~ ERROR constants cannot refer to statics [E0013]
fn main() {}

View File

@ -0,0 +1,11 @@
error[E0013]: constants cannot refer to statics
--> $DIR/E0013.rs:2:16
|
LL | const Y: i32 = X;
| ^
|
= help: consider extracting the value of the `static` to a `const`, and referring to that
error: aborting due to previous error
For more information about this error, try `rustc --explain E0013`.

View File

@ -0,0 +1,8 @@
fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some();
//~^ ERROR cannot call non-const fn `create_some` in constants [E0015]
fn main() {}

View File

@ -0,0 +1,11 @@
error[E0015]: cannot call non-const fn `create_some` in constants
--> $DIR/E0015.rs:5:25
|
LL | const FOO: Option<u8> = create_some();
| ^^^^^^^^^^^^^
|
= note: calls in constants are limited to constant functions, tuple structs and tuple variants
error: aborting due to previous error
For more information about this error, try `rustc --explain E0015`.