rust / intermediate
Snippet
Const Functions: Compile-Time Computation
Const functions execute at compile time when called in const contexts, enabling true zero-cost abstractions. Unlike C++ constexpr, Rust const fn has stricter rules but is fully evaluated at compile time for constant arguments. This enables performance-critical constants to be computed once during compilation rather than at runtime. The factorial and fibonacci examples demonstrate recursive and iterative const fn patterns. Since Rust 1.46, most control flow constructs are allowed in const fn, making complex compile-time calculations possible.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const fn factorial(n: u64) -> u64 {match n {0 | 1 => 1,n => n * factorial(n - 1),}}const fn fibonacci(n: u32) -> u64 {let mut a: u64 = 0;let mut b: u64 = 1;let mut result: u64 = 0;let mut i: u32 = 0;while i < n {result = a + b;a = b;b = result;i += 1;}if n <= 1 { a + b } else { result }}const FIB_20: u64 = fibonacci(20);const FACT_12: u64 = factorial(12);fn main() {println!("Fibonacci(20) = {}", FIB_20);println!("Factorial(12) = {}", FACT_12);}
Breakdown
1
const fn factorial(n: u64) -> u64
Function callable in const contexts—evaluated at compile time when arguments are constants
2
const FIB_20: u64 = fibonacci(20)
Const item initialized at compile time—no runtime cost for computation
3
let mut i: u32 = 0; while i < n {...}
While loops and mutable variables allowed in const fn since Rust 1.46