const

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

  1. const DIGEST_SIZE: usize = 3;
  2. const ZERO: Option<u8> = Some(42);
  3. fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
  4.     let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];
  5.     for (idx, &b) in text.as_bytes().iter().enumerate() {
  6.         digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
  7.     }
  8.     digest
  9. }
  10. fn main() {
  11.     let digest = compute_digest("Hello");
  12.     println!("digest: {digest:?}");
  13. }

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.