Common Standard Macros
assert!
The assert! macro evaluates a boolean expression at runtime and panics if the expression evaluates to false, verifying invariants in both debug and release builds.
Syntactic Forms
assert!(condition);
assert!(condition, "custom format string: {}", arg);
- If
conditionistrue,assert!does nothing and evaluates to(). - If
conditionisfalse,assert!panics, printing either the stringified expression (assertion failed: condition) or your custom formatted message along with the source file and line number.
fn compute_discount_price(price_cents: u64, discount_pct: u8) -> u64 {
assert!(
discount_pct <= 100,
"discount percentage must be in 0..=100, got {discount_pct}%"
);
price_cents * u64::from(100 - discount_pct) / 100
}
fn main() {
let final_price = compute_discount_price(2_000, 25);
println!("Discounted price: {final_price} cents");
}
Discounted price: 1500 cents
Panicking Output When assert! Fails
When compute_discount_price(2_000, 150) is called with an invalid percentage, assert! halts execution with the custom formatted message:
fn main() {
let discount_pct = 150_u8;
assert!(
discount_pct <= 100,
"discount percentage must be in 0..=100, got {discount_pct}%"
);
}
thread 'main' panicked at src/main.rs:3:5:
discount percentage must be in 0..=100, got 150%
Helping the Optimizer Eliminate Bounds Checks with assert!
Because assert!(index < slice.len()) (or assert!(slice.len() >= 4)) guarantees that execution cannot proceed past the assert! if the condition is false, the LLVM optimizer uses that proven fact to eliminate subsequent array bounds checks in the same function:
pub fn sum_first_four(data: &[u32]) -> u32 {
// Proves to LLVM once that `data` has at least 4 elements;
// the 4 indexing operations below compile with zero per-element bounds checks!
assert!(data.len() >= 4);
data[0] + data[1] + data[2] + data[3]
}
fn main() {
println!("Sum of first 4: {}", sum_first_four(&[10, 20, 30, 40, 50]));
}
Sum of first 4: 100