1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-28 00:26:44 +02:00
Dustin J. Mitchell 3291cb6c62
Make const slide less silly (#2557)
A constant named ZERO that does not contain zero seems pretty silly!

This also shows an example of a const fn.
2025-01-16 10:18:29 +01:00

1.2 KiB

minutes
10

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:?}");
}

According to the Rust RFC Book these are inlined upon use.

Only functions marked const can be called at compile time to generate const values. const functions can however be called at runtime.

  • Mention that const behaves semantically similar to C++'s constexpr
  • It isn't super common that one would need a runtime evaluated constant, but it is helpful and safer than using a static.