liveBook · Manning

Assert_eq

As explained in Learn Rust in a Month of Lunches

assert_eq! is a Rust macro that panics when two expressions evaluate to unequal values and reports both values.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains comparison, panic behavior, custom messages, collection checks, and test diagnostics without detailing macro expansion internals.
Examples
Demonstrates even-number validation, Vec mutations, custom messages, and failed tests comparing 2 with 3.
What it assumes
Assumes basic Rust expressions and introduces assertion macros through simple equality and collection examples.
What you can do after
Apply it to verify equal values and diagnose mismatches in Rust programs and tests.
How it connects
Connects assert_eq! with panic, assert!, testing, and Vec operations.

Also explained in

Compare how 2 books explain assert_eq →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.