Rust Reference ยท Macros
Rust debug_assert! macro
Reference for debug_assert!, debug_assert_eq! and debug_assert_ne! in Rust: checks that vanish in release builds, side-effect pitfalls and when to use them.
debug_assert! works like assert!, but its check only runs when debug assertions are enabled, which is the default for cargo build and cargo test and off for --release. Use it for sanity checks that are too costly to leave in optimized code, such as verifying that a list is still sorted after every insert.
The family is debug_assert!, debug_assert_eq! and debug_assert_ne!, with the same arguments as their assert cousins. Our runner compiles with debug assertions on, so they fire there.
debug_assert!(items.windows(2).all(|w| w[0] <= w[1]));
Try it
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.
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
debug_assert!(condition); debug_assert!(condition, "message {}", arg); debug_assert_eq!(left, right); debug_assert_ne!(left, right);
| Name | Description |
|---|---|
condition, left, right, message |
Exactly as for assert!. |
Returns: (). Panics: only when debug assertions are enabled and the check fails. In release builds the arguments are still type-checked but never evaluated.
Usage notes
- Controlled by
debug_assertions, not bydebugorreleasenames. You can turn it on in a release profile withdebug-assertions = true, or off in a dev profile. - No side effects. Code inside the condition does not run in release builds, so
debug_assert!(queue.pop().is_some())would change behavior. Keep conditions pure. - Use for invariants of your own code, not for validating user input; input errors must be handled in release builds too.
- Performance. An expensive loop in a debug assertion makes debug builds slow, though release stays untouched.
- Unused variables. Because the arguments are still type-checked in release, variables used only in a debug assertion do not trigger unused warnings.
- Check from code:
cfg!(debug_assertions)tells you whether they are on.