Const evaluation
Quick answer
Constant evaluation computes expressions in contexts that require compile-time values. It can define array sizes and validate simple configuration without waiting for program execution.
Const contexts and const fn
A const item and an array length are const contexts. A const fn can run in const contexts if its inputs and operations meet const-evaluation rules; the same function can also be called at runtime. Not every ordinary function or operation is allowed during constant evaluation on the pinned compiler.
const fn bytes_per_row(pixels: usize) -> usize { pixels * 4 }const ROW: usize = bytes_per_row(8);fn main() { let row = [0u8; ROW]; println!("{}", row.len()); }Expected stdout (not executed):
32The array length is computed in a const context.
const PORT: u16 = { assert!(false, "invalid port configuration"); 80 };fn main() { println!("{PORT}"); }Expected: compilation fails; exact diagnostic not verified.
This deliberately invalid constant cannot be compiled.
Common mistake
Declaring a function const does not guarantee every call happens at compile time.
Try it yourself
Write a const fn converting minutes to seconds and use it in a const item with a small safe input.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Const evaluation — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A const fn is called with an ordinary runtime argument. Is this allowed?
Const evaluation — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust const fn bytes_per_row(pixels: usize) -> usize { pixels * 4 } const ROW: usize = bytes_per_row(8); fn main() { let row = [0u8; ROW]; println!("{}", row.len()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Const evaluation — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust const PORT: u16 = { assert!(false, "invalid port configuration"); 80 }; fn main() { println!("{PORT}"); } ``` Which outcome or interpretation best matches this example?