Email me

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![..]; or String::from in 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

E0015Const, static and compile-time
Activein rustc 1.99.0
2related errors linked below

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

All 518 Rust error codes · Rust crate data · Glossary

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?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ