Assert And Debug Assert Guard Invariants

assert!, assert_eq!, assert_ne!, and debug_assert! turn broken invariants into panics carrying the values and messages needed to diagnose them.

RustData Integrity

Code

rustsnippet
23 lines
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");
}

How it works

Assert And Debug Assert Guard Invariants reduces to the functions validate and main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Signature: fn validate(order: (u32, u32)

The demo output is labeled (total:, computed matches expectation, all invariants held), so every printed line maps back to its originating operation.

The entry point wires validate together — run it once and the whole demo flows.

The key statements that remain

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
}

Interactive Tools for This Topic

FAQ

What does Assert And Debug Assert Guard Invariants print when run?
Execute the whole file; each printed line is prefixed with a label like `total:`, `computed matches expectation`, `all invariants held`.