← 中文资源

简体中文版本

const 项在编译期求值

const 常量、const fn 与用常量表达式定尺寸的 static 数组:退避延迟表全部在编译期算完,运行时只读结果。

阅读英文原文

实现说明

全部逻辑都在函数 retry_delay、main中。 文件的主干是一个循环——for (attempt, delay) in DELAYS.iter().enumerate()。

使用要点

  • 直接运行文件,输出会带上标签,比如 budget:、attempt、planned:——输出的每一行都能指回产生它的那次调用。
  • main 按顺序串起 retry_delay;运行文件就会把这个流程跑一遍。

常见问题

运行「const 项在编译期求值」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 budget:、attempt、planned: 标签标明各步骤。

签名一览:fn retry_delay(attempt: u32) -> u64

核心语句

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...
}

代码示例

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