In a Rust unit test, why does `assert_eq!(to_cents(135), Cents(14))` fail to compile until `Cents` derives `PartialEq` and `Debug`?
answer
- look at what the macro expands to
- a comparison operator inside
- the failure path formats both sides
- E0369 and E0277
basics
~10 sassert_eq! compares its arguments with ==, which needs PartialEq, and on failure prints both with {:?}, which needs Debug. A bare struct has neither, so rustc reports E0369 and E0277; #[derive(PartialEq, Debug)] fixes both.
solid answer
~40 s`assert_eq!(left, right)` takes references to both values and checks `*left == *right`, so the left type must implement `PartialEq` for the right type; on failure it calls a panic helper bounded by `Debug` that prints both values with `{:?}`. A plain `struct Cents(i64)` has neither trait, so rustc reports E0369 (binary operation `==` cannot be applied) and E0277 (doesn't implement `Debug`); `#[derive(Debug, PartialEq)]` fixes both. `assert_ne!` has the same needs with the test inverted. `assert!` takes a `bool`, needs neither trait and prints only the expression text, which is why `assert_eq!` is preferred for comparisons. All of them take a trailing format string as a custom message, and none is disabled in release builds.
code
rust · 18 lines#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cents(pub i64);
// Bug: truncates instead of rounding half to even.
pub fn to_cents(tenths: i64) -> Cents {
Cents(tenths.div_euclid(10))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn half_cent_rounds_to_even() {
let tenths = 135;
assert_eq!(to_cents(tenths), Cents(14), "rounding {tenths} tenths");
}
}go deeper
Recall that assert_eq! compares with == and prints both values on failure, so your own types need #[derive(PartialEq, Debug)].
Explain the expansion: references to both arguments, a PartialEq comparison, and a Debug-bounded panic helper, and how that differs from assert! printing only the expression.
Show you write tests whose failures diagnose themselves: assert_eq! over assert!, messages that carry the input, assert_matches! where only the shape matters.
Treat failure output as part of test quality: a suite whose failures need a debugger to read slows every engineer, so set expectations for assertion choice and messages.
## The failing test In a currency-rounding module, a newcomer writes a newtype for whole cents and a first test: ```rust pub struct Cents(pub i64); #[test] fn half_cent_rounds_to_even() { assert_eq!(to_cents(135), Cents(14)); } ``` rustc refuses it with two kinds of error: **E0369**, "binary operation `==` cannot be applied to type `Cents`", and **E0277**, "`Cents` doesn't implement `Debug`". The help notes suggest the two repairs: annotate `Cents` with `#[derive(PartialEq)]` and with `#[derive(Debug)]`. To see why, look at what the macro expands to. ## What `assert_eq!` expands to `assert_eq!` is a declarative macro in `core`. It matches on `(&left, &right)`, compares `*left_val == *right_val`, and on a mismatch calls an internal panic helper with both references. Written as an ordinary function, it behaves like this: ```rust use std::fmt::Debug; fn assert_eq_like<T: PartialEq<U> + Debug, U: Debug>(left: &T, right: &U) { if !(*left == *right) { panic!("assertion `left == right` failed left: {left:?} right: {right:?}"); } } ``` Two requirements fall out of that code: - **`==` needs `PartialEq`.** The comparison is `*left_val == *right_val`, so the left type must implement `PartialEq` for the right type. A plain struct implements no comparison at all, hence E0369. The two sides may be different types if such an impl exists: `assert_eq!(String::from("12.50"), "12.50")` compiles, while comparing an `i64` with an `i32` fails with E0308 because no impl connects them. - **The failure path needs `Debug`.** The panic helper is declared with `T: fmt::Debug` and `U: fmt::Debug`, because it prints both values with `{:?}`. That bound is checked even if the assertion would never fail, hence E0277. The macro takes **references** to its arguments, so it never moves them; you can keep using both values after the assertion. ## Reading the failure With `#[derive(Debug, PartialEq)]` on `Cents` and a buggy `to_cents` that truncates instead of rounding, the test now compiles and fails like this: ```plaintext assertion `left == right` failed: rounding 135 tenths left: Cents(13) right: Cents(14) ``` The header names the comparison, the custom message follows the colon, and both values follow in their `Debug` form. That is the whole reason to prefer `assert_eq!(a, b)` over `assert!(a == b)`. ## Choosing an assertion macro | Macro | Passes when | Needs | Prints on failure | |---|---|---|---| | `assert!(cond)` | `cond` is `true` | nothing beyond `bool` | `assertion failed: <expression text>`, or only the custom message | | `assert_eq!(a, b)` | `a == b` | `PartialEq`, `Debug` | header plus `left:` and `right:` values | | `assert_ne!(a, b)` | `a != b` | `PartialEq`, `Debug` | header with `left != right`, plus both values | | `assert_matches!(v, pattern)` | `v` matches the pattern | `Debug` | header with `left matches right`, the value and the pattern | `assert_matches!` was stabilised in **Rust 1.96**; it is not in the prelude, so a test imports it with `use std::assert_matches;`. It accepts the same patterns as a `match` arm, including guards, and suits checks on a variant or a range where exact equality is too strict. ## Custom failure messages All four macros accept extra arguments after the required ones, passed to `format_args!` like a `println!` call: 1. Put the context the bare values lack into the message: the input, the loop index, the case name. 2. Use inline arguments, as in `"rounding {tenths} tenths"`; they capture variables in scope. 3. Expect the message to be **added**, not substituted: `assert_eq!` still prints both values after it. `assert!` with a message prints only the message, so include the values yourself. ## Always on `assert!`, `assert_eq!`, `assert_ne!` and `assert_matches!` are checked in **both debug and release builds** and cannot be disabled. Their `debug_assert_*` twins expand to `if cfg!(debug_assertions) { ... }`, so they are still type-checked but skip the check when debug assertions are off, which is the default for release builds. Inside a unit test the difference rarely matters, but it does in library code that uses assertions as runtime guards. ## Common slips - Deriving only `PartialEq` and then meeting E0277 for `Debug` on the next build. - Writing `assert!(a == b)` and getting a failure that shows the expression but neither value. - Assuming the custom message replaces the `left:` and `right:` lines; it is printed in addition to them.
- What exactly does a failing `assert_eq!` with a custom message print?A header ``assertion `left == right` failed:`` followed by the formatted message, then a `left:` line and a `right:` line with each value's `Debug` output. The message is added to the default output, not substituted for it, so the values are still shown.
- When would you reach for `assert_matches!` instead of `assert_eq!`?When the test cares about shape rather than exact equality: a variant, a range such as `Cents(13..=14)`, or a guard. It needs only `Debug`, not `PartialEq`, and prints the value and the pattern on failure. It is stable since Rust 1.96 and must be imported with `use std::assert_matches;`.
- assert_eq! compares the two values' memory addresses.
- assert_eq! needs only PartialEq; Debug is optional.
- assert! prints both compared values when it fails.
- assert_eq! is disabled in release builds, just like debug_assert_eq!.
- A custom message replaces the left and right values in the output.
Assumes Rust 1.99; assert_matches! is stable since 1.96 and the rest of the answer holds on every current stable release.