rust const-eval ai_generated true

error[E0015]: cannot call non-const fn in constants

ID: rust/e0015-cannot-call-non-const-fn

Also available as: JSON · Markdown
91%Fix Rate
93%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Trying to call a runtime function in a const context (const, static, or const fn).

generic

Workarounds

  1. 93% success Use lazy_static! or std::sync::LazyLock for runtime-initialized static values
    lazy_static! { static ref DATA: Vec<i32> = compute(); }

    Sources: https://doc.rust-lang.org/std/sync/struct.LazyLock.html

  2. 85% success Move the initialization to a const fn if possible
    Mark the function as const fn if all its operations are const-evaluable

Dead Ends

Common approaches that don't work:

  1. Using unsafe to bypass the const restriction 90% fail

    unsafe doesn't make non-const functions callable in const context

  2. Using a different type that has const constructors 55% fail

    May not be functionally equivalent

Error Chain

Frequently confused with: