Rust errors / Const, static and compile-time
Rust compiler error · checked with rustc 1.99.0
Rust error E0015: cannot call non-const fn in constants
What it meansA const or static initializer calls a function that cannot run at compile time.
What rustc prints
error[E0015]: cannot call non-const function `create_some` in constants --> main.rs:6:25 | 6 | const FOO: Option<u8> = create_some(); | ^^^^^^^^^^^^^ | note: function `create_some` is not const --> main.rs:1:1 | 1 | fn create_some() -> Option<u8> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: calls in constants are limited to constant functions, tuple structs and tuple variants
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
Why it happens
static NAMES: Vec<String> = vec![..];orString::fromin a const.- Building a HashMap or Regex in a static.
How to fix it
1. Use LazyLock
Std has lazy statics since Rust 1.80.
use std::sync::LazyLock;
static RE: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(r"\d+").unwrap());Other wordings of this error
cannot call non-const fn in constants, calls in constants are limited to constant functions, cannot call non-const
The compiler team's explanation
A non-const function was called in a const context.
Erroneous code example:
fn create_some() -> Option<u8> {
Some(1)
}
// error: cannot call non-const function `create_some` in constants
const FOO: Option<u8> = create_some();
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:
// declared as a `const` function:
const fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some(); // no error!From rustc --explain E0015 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
Up next
Often hit nextE0080: attempt to shift left by `500_i32`, which would overflowA related error from the same family.Read it next →Did this answer your question?