const

Constants are evaluated at compile time and their values are inlined wherever they are used:

const DIGEST_SIZE: usize = 3;
const FILL_VALUE: u8 = calculate_fill_value();

const fn calculate_fill_value() -> u8 {
    if DIGEST_SIZE < 10 { 42 } else { 13 }
}

fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
    let mut digest = [FILL_VALUE; DIGEST_SIZE];
    for (idx, &b) in text.as_bytes().iter().enumerate() {
        digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
    }
    digest
}

fn main() {
    let digest = compute_digest("Hello");
    println!("digest: {digest:?}");
}

根据 Rust RFC Book 这些变量在使用时是内联 (inlined) 的。

在编译时只能调用标记为“const”的函数以生成“const”值。不过,可在运行时调用“const”函数。

This slide should take about 10 minutes.
  • Mention that const behaves semantically similar to C++’s constexpr