Assert Macros
In this page:
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
fn main() {
let value = 10;
assert!(value > 0);
println!("Assertion passed: value is positive");
}
Login to try C/C++/Java/PHP code in the editor
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
fn square(n: i32) -> i32 {
n * n
}
fn main() {
assert_eq!(square(4), 16);
println!("Assertion passed: square(4) == 16");
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let original = 5;
let modified = original + 1;
assert_ne!(original, modified);
println!("Assertion passed: values are different");
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let count = 3;
assert!(count > 0, "count must be positive, got {}", count);
println!("Assertion passed with count = {}", count);
}
Login to try C/C++/Java/PHP code in the editor
- Using
assert_eq!with values that don't implementDebug, since the macro needsDebugto print both sides on failure. - Confusing
assert!(checks a single boolean) withassert_eq!/assert_ne!(compares two values). - 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.
assert!(condition)panics if the condition is false.assert_eq!(a, b)panics ifaandbare not equal, printing both values for easy debugging.assert_ne!(a, b)panics ifaandbare 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: