liveBook · Manning

Assertion

As explained in Learn Rust in a Month of Lunches

A software assertion is an executable check of an expected condition or property that signals failure when the check does not hold.

An assertion checks a condition your program expects to hold. If the check fails, Rust panics, making a logic bug visible instead of letting the program continue unnoticed. section 6.3

Rust provides three assertion macros:

  • assert! checks that a condition is true. section 6.3
  • assert_eq! checks that two values are equal; assert_ne! checks that they are not equal. section 6.3
  • Each macro can take a custom message, displayed if the assertion fails. section 6.3
fn main() {
    let my_name = "Loki Laufeyson";
 
    assert!(my_name == "Loki Laufeyson");
    assert_eq!(my_name, "Loki Laufeyson");
    assert_ne!(my_name, "Mithridates");
}

These checks pass because the name matches the expected value and differs from Mithridates. section 6.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines three assertion macros and demonstrates passing checks, custom failure messages, and panic output.
Examples
Checks a vector's expected length and compares a name with expected and disallowed values.
What you can do after
Apply Rust's assertion macros to check conditions and equality or inequality in code.
How it connects
Connects assertions to panics, logic bugs, and testing.

Also explained in

Compare how 15 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.