71. Inline const Blocks — Compile-Time Evaluation Anywhere
Need a compile-time value in the middle of runtime code? Wrap it in const { } and the compiler evaluates it on the spot — no separate const item needed.
The old way
When you needed a compile-time constant inside a function, you had to hoist it into a separate const item:
| |
It works, but the const declaration is noisy — especially when you only use the value once and it clutters the function body.
Enter const { }
Since Rust 1.79, you can write const { expr } anywhere an expression is expected. The compiler evaluates it at compile time and inlines the result:
| |
No named constant, no separate item — just an inline compile-time expression right where you need it.
Generic compile-time values
const { } really shines inside generic functions, where it can compute values based on type parameters:
| |
The const { assert!(...) } fires at compile time for each monomorphization — if someone writes make_mask::<200>(), they get a compile error, not a runtime panic.
Compile-time assertions
Use const { } to embed compile-time checks directly in your code:
| |
The assertion runs at compile time — if it fails, you get a compile error, not a runtime panic. It’s like a lightweight static_assert from C++, but it works anywhere.
Building lookup tables
const { } shines when you need a precomputed table without polluting the outer scope:
| |
The array is built at compile time and the contains check runs at runtime — clean, fast, and self-contained.
Next time you’re about to write const TEMP: ... = ...; just to use it once, reach for const { } instead. It keeps the value where it belongs — right at the point of use.