`assert!`
assert! panics if a boolean is false. In tests that failure is a failed test. In application code it is a crash you should reserve for broken invariants.
Detailed Explanation
assert!(ready) is if !ready { panic!(...) }. The default message includes the file and line. assert!(ready, "session {id} not ready") adds a format string. There is no assertTrue versus assertFalse; you write assert!(!closed).
In a #[test], a panic is a failure. assert! is the boolean check. Prefer assert_eq! when two values should be equal; the panic message then prints both sides. assert! is for predicates that are not equalities: assert!(port > 1024), assert!(path.exists()).
assert! is not stripped in release builds. debug_assert! is. Use assert! for invariants that must hold in production (a checksum you just computed). Use debug_assert! for expensive checks you can afford only in tests and dev (an O(n) validation of a structure). Do not use either for user input; return Result.
assert! in a library's happy path is a contract: if it fires, the caller or the library has a bug. That is different from unwrap on a Result that came from the network. Reviewers should treat a new assert! as a statement about invariants, not as a substitute for error handling.
When you write assert!: a boolean invariant in a test or a cheap production check. When you write assert_eq!: two values. When you write Result: the failure is expected and should be handled.
Chain nothing after an assert! that you need on failure. The process is gone. For tests that must clean a tempdir, use a Drop guard or tempfile so cleanup runs during unwind. assert! is not return Err. In application code, an assert that can fire on a production input is a support incident, not a log line.
Code Examples
fn is_high(port: u16) -> bool {
port > 1024
}
fn main() {
assert!(is_high(8080));
assert!(!is_high(80), "80 should be privileged");
println!("ok");
}Common Gotchas
`assert!` is live in release
An expensive assertion in a hot path belongs in `debug_assert!` or a test.
Do not `assert!` user input
A bad port from a config file is `Err`, not a panic in a library function.
`assert!(a == b)` is a worse `assert_eq!`
You lose the printed values. Use `assert_eq!`.
The message is formatted only on failure
A format argument that is expensive still runs only when the assert fails.