const items are values known at compile time, and static items have a fixed address. A const fn can be called in constant expressions, such as FIB_20.
A block in a const can compute a lookup table, like SQUARES. const { ... } inside a function forces an expression to be evaluated at compile time.
Const generics make a value part of a type: Ring<T, const N: usize> has a capacity fixed at compile time.
The design adds wider compile-time evaluation than Rust’s. It’s planned to run on the same sandboxed engine as procedural macros, so code evaluated at compile time can’t do I/O.
09_const_eval.ox
// Compile-time evaluation. `const fn` runs in the sandboxed compile-time
// engine, the same one that runs procedural macros.
const MAX_PLAYERS: usize = 16;
static GAME_NAME: &str = "example";
const fn fib(n: u32) -> u64 {
let mut a = 0;
let mut b = 1;
let mut i = 0;
while i < n {
let next = a + b;
a = b;
b = next;
i += 1;
}
a
}
const FIB_20: u64 = fib(20);
// Lookup tables built at compile time.
const SQUARES: [u32; 8] = {
let mut table = [0; 8];
let mut i = 0;
while i < 8 {
table[i] = (i * i) as u32;
i += 1;
}
table
};
// Const generics.
struct Ring<T, const N: usize> {
items: [Option<T>; N],
head: usize,
}
impl<T, const N: usize> Ring<T, N> {
const CAPACITY: usize = N;
}
fn inline_const() -> u64 {
const { fib(30) } // forced compile-time evaluation
}