Const Items Evaluate At Compile Time

Declare typed constants, const fns, and a static array sized by a const expression so the backoff table is computed during compilation.

RustConfig Management

Code

rustsnippet
29 lines
// const:编译期常量,必须标注类型;命名用 SCREAMING_SNAKE_CASE
const MAX_RETRIES: u32 = 3;
const TIMEOUT_SECS: u64 = 30;

// 常量表达式:const 之间的算术在编译期求值
const TOTAL_BUDGET_SECS: u64 = MAX_RETRIES as u64 * TIMEOUT_SECS;

// const fn:可在编译期调用的函数
const fn retry_delay(attempt: u32) -> u64 {
    1u64 << attempt // 指数退避:1, 2, 4, 8...
}

// 数组长度要求编译期常量:这里用 const 表达式定尺寸
const SLOTS: usize = MAX_RETRIES as usize;
static DELAYS: [u64; SLOTS] = [
    retry_delay(0),
    retry_delay(1),
    retry_delay(2),
];

fn main() {
    println!("budget: {TOTAL_BUDGET_SECS}s");
    for (attempt, delay) in DELAYS.iter().enumerate() {
        println!("attempt {attempt}: wait {delay}s");
    }
    // const fn 也可在运行时调用,只是它保证编译期可求值
    let planned = retry_delay(3);
    println!("planned: {planned}s");
}

Inside the snippet

Const Items Evaluate At Compile Time keeps everything in the functions retry_delay and main.

The loop for (attempt, delay) in DELAYS.iter().enumerate() is the only repeated construct.

Using it

The primary signature is fn retry_delay(attempt: u32) -> u64

The demo output is labeled (budget:, attempt, planned:), so every printed line maps back to its originating operation.

main is the driver: it invokes retry_delay before returning.

Key statements

for (attempt, delay) in DELAYS.iter().enumerate() {
    println!("attempt {attempt}: wait {delay}s");
}
const fn retry_delay(attempt: u32) -> u64 {
    1u64 << attempt // 指数退避:1, 2, 4, 8...
}

Interactive Tools for This Topic

FAQ

What does Const Items Evaluate At Compile Time print when run?
The script runs standalone; its 3 labeled outputs include `budget:`, `attempt`, `planned:`.