Improve E0015 long error explanation

This commit is contained in:
Guillaume Gomez 2019-11-22 13:23:33 +01:00
parent f1b882b558
commit ea62c2e5b3

View file

@ -1,14 +1,32 @@
A constant item was initialized with something that is not a constant expression.
Erroneous code example:
```compile_fail,E0015
fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some(); // error!
```
The only functions that can be called in static or constant expressions are
`const` functions, and struct/enum constructors. `const` functions are only
available on a nightly compiler. Rust currently does not support more general
compile-time function execution.
`const` functions, and struct/enum constructors.
To fix this error, you can declare `create_some` as a constant function:
```
const FOO: Option<u8> = Some(1); // enum constructor
struct Bar {x: u8}
const BAR: Bar = Bar {x: 1}; // struct constructor
const fn create_some() -> Option<u8> { // declared as a const function
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};
```
See [RFC 911] for more details on the design of `const fn`s.
[RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md