assert_eq! compares two expressions and panics when their values are unequal. When the values match, execution continues, making the macro useful for checking guarantees and test expectations. section 6.3 section 13.1.1
Checking a number
fn prints_number(input: i32) { assert_eq!(input % 2, 0); println!("The number is not odd. It is {input}"); } For input 56, the remainder is zero, so the assertion succeeds and the message prints. section 13.1.1
Use assert_eq! to:
- State that two values should be the same at a particular point in the program. section 13.1.1
- Check collection length, indexing, removal results, mutation, and final contents. section 13.1.1
- Read a failure that identifies the left value and the right value, such as 2 versus 3. section 14.2.2
- Add a custom message when a failed check needs extra context; the message appears only after a panic. section 6.3
fn main() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);
assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);
vec[0] = 7;
assert_eq!(vec[0], 7);
vec.extend([1, 2, 3].iter().copied());
for x in &vec {
println!("{}", x);
}
assert_eq!(vec, [7, 1, 2, 3]);
}
A compact sequence of assertions follows a Vec through insertion, removal, mutation, extension, and final comparison. section 13.1.1
In tests, assert_eq! is one of the common ways to verify a function. If it fails, the test reports the assertion, values, source location, and optionally a backtrace through RUST_BACKTRACE. section 14.2.2

