← 中文资源

简体中文版本

Duration 的 checked 运算守预算

checked_add 与 checked_sub 返回 Option 而不是 panic 或回绕:Duration 不可能为负,减出负数会被拦成 None,超出预算同样一目了然。

阅读英文原文

实现说明

Duration 的 checked 运算守预算以函数 main为骨架。 这里的控制流就是 match:分支穷尽地列出值的形态。

使用要点

  • 直接运行文件,输出会带上标签,比如 within cap:、exceeds cap:、overflow——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Duration 的 checked 运算守预算」会打印什么?

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

核心语句

match measured.checked_add(jitter) {
    Some(total) if total <= cap => println!("within cap: {total:?}"),
    Some(total) => println!("exceeds cap: {total:?}"),
    None => println!("overflow"),
}

代码示例

use std::time::Duration;

fn main() {
    let cap = Duration::from_secs(60);
    let measured = Duration::from_millis(59_500);
    let jitter = Duration::from_millis(900);

    // checked_add 在溢出时返回 None:不会绕回成更小的值
    match measured.checked_add(jitter) {
        Some(total) if total <= cap => println!("within cap: {total:?}"),
        Some(total) => println!("exceeds cap: {total:?}"),
        None => println!("overflow"),
    }

    // checked_sub 防止 Duration 下溢(Duration 不可能有负值)
    let spent = Duration::from_secs(90);
    println!("budget - spent: {:?}", cap.checked_sub(spent));

    let small = Duration::from_millis(500);
    println!("budget - small: {:?}", cap.checked_sub(small));
}