rust
const_error
ai_generated
true
error[E0015]: cannot call non-const fn in const context
ID: rust/e0015-non-const-fn
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1 | active | — | — | — |
Root Cause
Calling a runtime function in a const/static context. Not all functions can run at compile time.
genericWorkarounds
-
92% success Use lazy_static! or std::sync::LazyLock for runtime-initialized global values
use std::sync::LazyLock; static CACHE: LazyLock<HashMap<String, i32>> = LazyLock::new(|| HashMap::new());
Sources: https://doc.rust-lang.org/std/sync/struct.LazyLock.html
-
85% success Move initialization from const/static to a function that runs at startup
use std::sync::OnceLock; static CONFIG: OnceLock<Config> = OnceLock::new(); fn get_config() -> &'static Config { CONFIG.get_or_init(|| { Config::load() // non-const initialization at first access }) }Sources: https://doc.rust-lang.org/reference/const_eval.html
Dead Ends
Common approaches that don't work:
-
Make every function const
80% fail
Most functions can't be const — they allocate, do IO, or have side effects
-
Use unsafe to bypass const restrictions
90% fail
unsafe doesn't override const restrictions
Error Chain
Frequently confused with: