assert! macro
- Rust course
- Intermediate
- Lesson 84/115
- 4 min
Assert with assert!, assert_eq! and assert_ne!.
assert! macros
There are three basic check macros; all panic on failure and accept an optional message:
assert!(tek_mi(3)); // the condition must be true
assert_eq!(tek_mi(4), false); // the two values must be equal
assert_ne!(kare(3), 6, "kare yanlış: {}", kare(3)); // must not be equalassert_eq! and assert_ne! print both values on failure, which is why the values need Debug and PartialEq.
debug_assert!
The debug_assert! family only runs in debug builds; it's removed entirely in a release build. It's used for expensive internal consistency checks:
fn ortalama(v: &[f64]) -> f64 {
debug_assert!(!v.is_empty(), "boş dilim");
v.iter().sum::<f64>() / v.len() as f64
}Checks required for safety or correctness must stay as assert!; debug_assert! is only for catching "should never happen" cases early.
Practice Checks
Write fn tek_mi(n: i32) -> bool and fn kare(n: i32) -> i32. In main, run the checks assert!(tek_mi(3)), assert_eq!(tek_mi(4), false) and a assert_ne!(kare(3), 6, ..) with a message, then print denetimler tamam.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn tek_mi(n: i32) -> bool {
n % 2 != 0
}
fn kare(n: i32) -> i32 {
n * n
}
fn main() {
assert!(tek_mi(3));
assert_eq!(tek_mi(4), false);
assert_ne!(kare(3), 6, "kare yanlış: {}", kare(3));
println!("denetimler tamam");
}Expected output
denetimler tamam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does <code>assert_eq!(0.1 + 0.2, 0.3)</code> fail when testing floating-point results?
- Floating-point error: 0.1 + 0.2 = 0.30000000000000004 Correct answer
- assert_eq! doesn't accept f64
- It passes
- It doesn't compile
Explanation: Floats are compared with a tolerance: assert!((a - b).abs() < 1e-9).
2 Must not be equal
____(kare(3), 6, "kare yanlış");
assert_ne!(kare(3), 6, "kare yanlış");
Explanation: assert_ne! panics if the two values are equal.
3 Macro and failure condition
| Term | Meaning |
|---|---|
assert!(k) |
k is false |
assert_eq!(a, b) |
a != b |
assert_ne!(a, b) |
a == b |
debug_assert!(k) |
Only in debug |