Panic and assertions
Quick answer
A panic signals that execution cannot continue normally along the current path. Assertions check programmer assumptions, while ordinary invalid user input should usually return Result.
Assertions and panic strategy
assert! panics when its condition is false; assert_eq! compares two values. These remain enabled in release builds. debug_assert! is typically disabled in optimized builds unless configured otherwise. Panic can unwind or abort depending on the build and target; cleanup is not guaranteed on abort.
fn main() { let items = [2, 4, 6]; assert_eq!(items.len(), 3); println!("invariant holds");}Expected stdout (not executed):
invariant holdsThe known invariant holds and execution continues.
fn positive(n: i32) -> Result<i32, &'static str> { if n > 0 { Ok(n) } else { Err("not positive") }}fn main() { println!("{:?}", positive(-2)); }Expected stdout (not executed):
Err("not positive")A normal invalid input is a recoverable error.
Common mistake
Do not put required side effects inside debug_assert or assume all panics can be caught.
Try it yourself
Explain whether an absent user-entered name should be an assertion or a Result.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Panic and assertions — practice quiz
Choose one answer per question, then review the explanation.
What does `assert_eq!(2 + 3, 6)` do when reached?
Should ordinary assert! checks disappear by default in release builds?
Why avoid assuming a destructor runs after every panic?