const

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

const DIGEST_SIZE: usize = 3;
const ZERO: Option<u8> = Some(42);

fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
    let mut digest = [ZERO.unwrap_or(0); 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.

فقط توابعی که با const علامت گذاری شده اند می توانند در زمان کامپایل برای تولید مقادیر const فراخوانی شوند. با این حال، توابع const را می توان در زمان اجرا فراخوانی کرد (بر خلاف تعریف متغییری ثابت)

  • Mention that const behaves semantically similar to C++’s constexpr
  • با اینکه خیلی رایج نیست که اگر کسی به یک یک مقدار ثابت که در زمان اجرا ارزیابی می‌شود از const استفاده کند اما مفید تر و ایمن تر از استفاده staticها هستند.