← Back to Rust Course | Chapter 15: Cargo, Testing & Best Practices | Lesson 4 of 8

Assert Macros

Assert macros are little tripwires in your code that stop everything and complain loudly if something isn't true.

assert! for Boolean Conditions

assert!(condition) panics with a generic message if the given boolean expression evaluates to false, otherwise it does nothing.

Example: assert! for Boolean Conditions

markup
fn main() {
    let value = 10;
    assert!(value > 0);
    println!("Assertion passed: value is positive");
}

assert_eq! for Equality Checks

assert_eq!(left, right) panics if the two values are not equal, and importantly prints both values in the panic message, which makes debugging test failures much easier than a plain assert!.

Example: assert_eq! for Equality Checks

markup
fn square(n: i32) -> i32 {
    n * n
}

fn main() {
    assert_eq!(square(4), 16);
    println!("Assertion passed: square(4) == 16");
}

assert_ne! for Inequality Checks

assert_ne!(left, right) is the opposite of assert_eq!, panicking if the two values turn out to be equal when they were expected to differ.

Example: assert_ne! for Inequality Checks

markup
fn main() {
    let original = 5;
    let modified = original + 1;
    assert_ne!(original, modified);
    println!("Assertion passed: values are different");
}

Adding a Custom Panic Message

All three assert macros accept an optional format string and arguments after the main condition, producing a clearer, more specific panic message on failure.

Example: Adding a Custom Panic Message

markup
fn main() {
    let count = 3;
    assert!(count > 0, "count must be positive, got {}", count);
    println!("Assertion passed with count = {}", count);
}
Common Mistakes
  1. Using assert_eq! with values that don't implement Debug, since the macro needs Debug to print both sides on failure.
  2. Confusing assert! (checks a single boolean) with assert_eq!/assert_ne! (compares two values).
  3. Forgetting assert macros work outside of tests too, and will panic the whole program if their condition fails at runtime, not just during cargo test.
Chapter Summary
  • assert!(condition) panics if the condition is false.
  • assert_eq!(a, b) panics if a and b are not equal, printing both values for easy debugging.
  • assert_ne!(a, b) panics if a and b are equal.
  • All three macros work anywhere in a program, not just inside #[test] functions, and accept an optional custom panic message.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.