`assert_eq!`
assert_eq! panics if two values are not equal, and the panic message prints both sides with Debug. assert_ne! is the opposite check.
Detailed Explanation
assert_eq!(left, right) requires PartialEq and Debug. On failure you see left: 1, right: 2 (plus your optional message). That is why it beats assert!(left == right) in tests. assert_ne! fails when the values are equal.
Order is conventional: expected first or actual first is a team choice. Rust's macro names them left and right, not expected and actual. Pick a convention and keep it so a failing CI log is readable. Many teams write assert_eq!(got, 42) so the computed value is first; others do the reverse. Consistency matters more than which side.
Floating-point equality is a poor use. assert_eq!(0.1 + 0.2, 0.3) fails. Compare with an epsilon, or use a crate, or compare a rounded integer. NaN != NaN, so assert_eq! on f64 can fail for values you think are "the same missingness".
assert_eq! is not a matcher library. There is no assert_that!(list).contains(...). You write assert!(list.contains(&x)) or use pretty_assertions for coloured diffs, or insta for snapshots. Keep assert_eq! for values that implement Debug cleanly. A 10 KB struct dump is a bad failure message; assert the field you care about.
When you write assert_eq!: two values in a test. When you write assert!: a predicate. When you write a snapshot: a large string or tree that you update deliberately.
Compare the smallest interesting value. assert_eq!(user, expected_user) on a 20-field struct produces a wall of Debug. assert_eq!(user.id, 17) and assert_eq!(user.name, "ada") fail on the field that drifted. Snapshot crates exist for the whole struct when the whole struct is the contract.
Code Examples
fn parse_port(raw: &str) -> Result<u16, ()> {
raw.parse().map_err(|_| ())
}
#[test]
fn parses_numeric_port() {
assert_eq!(parse_port("8080"), Ok(8080));
assert_ne!(parse_port("8080"), Ok(80));
}Common Gotchas
The type needs `PartialEq` and `Debug`
A custom error without `Debug` will not compile in `assert_eq!`. Derive them.
Floats almost never want `assert_eq!`
Use a tolerance. The classic `0.1 + 0.2` demo fails for a reason.
Left and right are not named expected/actual
Agree a convention in the crate so failures scan quickly.
`pretty_assertions` replaces the panic format
Drop it in as a `use pretty_assertions::assert_eq` in tests when diffs are large.