Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust assert!, assert_eq! and assert_ne!

Reference for assert!, assert_eq! and assert_ne! in Rust: checking conditions, custom messages, Debug requirements, failure output and use in tests.

The assertion macros check a condition and panic if it is false. They are always compiled in, in debug and release builds alike. Use them to guard invariants that must hold for the program to be correct, and in tests to compare results.

assert!(cond) checks a boolean. assert_eq!(left, right) checks left == right and, on failure, prints both values. assert_ne! checks they differ. For the equality forms, both sides need PartialEq and Debug, and they must be comparable with each other.

Rust
assert!(x > 0);
assert_eq!(add(2, 2), 4);
assert_ne!(a, b, "a and b must differ");

Try it

Rust A passing assertion and a failing one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Comparing different types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
assert!(condition);
assert!(condition, "message {}", arg);
assert_eq!(left, right);
assert_eq!(left, right, "message {}", arg);
assert_ne!(left, right);
Name Description
condition A bool expression.
left, right Values compared with == (or !=). Both must implement Debug; left == right must be valid.
message Optional format string and arguments, shown if the assertion fails.

Returns: () when the check passes. Panics: when the condition is false. assert_eq! failure output shows left: and right: values (and your message).

Usage notes

  • Always on. Unlike debug_assert!, these run in release builds too. A hot loop with an expensive assertion may need debug_assert!.
  • Prefer assert_eq! to assert!(a == b): the failure message shows both values.
  • Floats. assert_eq! on f64 is exact; compare a difference with a tolerance instead. NaN != NaN, so assert_eq!(f64::NAN, f64::NAN) fails.
  • Evaluated once. Each argument is evaluated exactly once.
  • Message arguments are only evaluated on failure, so they can be costly.
  • Tests. Inside #[test] functions a failing assertion marks the test as failed.
  • Side effects. Never put needed side effects in the condition: it still runs in release builds, but for debug_assert! it would not.