← 中文资源

简体中文版本

断言与调试断言守护不变式

assert!/assert_eq!/assert_ne! 把被破坏的不变式变成携带两个值与格式化消息的 panic,debug_assert! 在 release 构建中整体移除。

阅读英文原文

实现说明

逻辑集中在函数 validate、main里。

使用要点

  • 演示输出是带标签的(total:、computed matches expectation、all invariants held),每个操作都会留下自己的一行标注。
  • main 的演示流程是 validate——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「断言与调试断言守护不变式」会打印什么?

整个文件跑完,输出行以 total:、computed matches expectation、all invariants held 这类前缀开头。

主签名形如 fn validate(order: (u32, u32)

核心语句

fn validate(order: (u32, u32)) -> u32 {
    let (id, quantity) = order;
    // assert! guards a precondition with a formatted message
    assert!(quantity > 0, "order {id} has zero quantity");
    assert!(id < 10_000, "order id {id} out of catalog range");
    id * quantity
}

代码示例

fn validate(order: (u32, u32)) -> u32 {
    let (id, quantity) = order;
    // assert! guards a precondition with a formatted message
    assert!(quantity > 0, "order {id} has zero quantity");
    assert!(id < 10_000, "order id {id} out of catalog range");
    id * quantity
}

fn main() {
    println!("total: {}", validate((7, 3)));

    // assert_eq! compares two values and prints both sides on failure
    let computed = validate((9, 2));
    assert_eq!(computed, 18);
    println!("computed matches expectation");

    // assert_ne! is the inverted form for exclusion checks
    assert_ne!(computed, 0);

    // debug_assert! compiles away in release builds
    debug_assert!(computed > 0, "totals must be positive");
    println!("all invariants held");
}