programming-language-rust-const.html


* created: 2025-10-15T12:05
* modified: 2025-10-16T18:30

title

Const

description

`const` values are compile-time constants that are **immutable** and have a value that must be determinable at compile time.

I need some constants in live

const values are immutable values that are evaluated at compile time. This means runtime values or function calls can't be used (except for const fn); furthermore they must have an explicit type.

Constants are inlined directly into the code wherever they're used, rather then stored in a specific memory location.

const BUFFER_SIZE: usize = 8192;
let buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];

It is possible to scope const values inside a function:

fn calculate_circle_area(radius: f64) -> f64 {
    const PI: f64 = 3.14159265359;
    PI * radius * radius
}

Const Functions

These are functions that can be evaluated at compile time. This means they can be used to compute const values or in other compile-time contexts.

They come with the following restrictions:

const fn square(x: i32) -> i32 {
    x * x
}

// Can use in const declarations
const FOUR_SQUARED: i32 = square(4); // Computed at compile time

// Can also call at runtime
fn main() {
    let result = square(5); // Computed at runtime
}

Associated Constants in Traits

Defining constants as part of a trait, so that implementors can provide their own values.

trait Database {
    const MAX_CONNECTIONS: usize;
    const TIMEOUT_SECS: u64;
}

struct PostgresDB;

impl Database for PostgresDB {
    const MAX_CONNECTIONS: usize = 100;
    const TIMEOUT_SECS: u64 = 30;
}

struct RedisDB;

impl Database for RedisDB {
    const MAX_CONNECTIONS: usize = 1000;
    const TIMEOUT_SECS: u64 = 5;
}

fn create_pool<DB: Database>() -> ConnectionPool {
    ConnectionPool::new(DB::MAX_CONNECTIONS, DB::TIMEOUT_SECS)
}