Common Standard Macros

assert_ne!

The assert_ne! macro asserts that two expressions are not equal (left != right via PartialEq), and if they are equal, panics and prints the Debug ({:?}) values of both operands along with an optional custom message.

Syntax and Trait Requirements

assert_ne!(left, right);
assert_ne!(left, right, "custom format string: {}", arg);

Like assert_eq!, assert_ne! requires both operands to implement PartialEq (for !=) and std::fmt::Debug (so the offending equal value can be formatted in the panic output). Both left and right are borrowed (&left, &right) and evaluated exactly once.

Verifying Distinct IDs, Nonces, and State Transitions

struct IdGenerator {
    next: u64,
}

impl IdGenerator {
    fn new(seed: u64) -> Self {
        Self { next: seed }
    }

    fn generate(&mut self) -> u64 {
        let id = self.next;
        self.next += 1;
        id
    }
}

fn main() {
    let mut gen = IdGenerator::new(1000);
    let id1 = gen.generate();
    let id2 = gen.generate();

    assert_ne!(id1, id2, "consecutive IDs must be distinct");
    println!("Generated distinct IDs: {id1} and {id2}");
}
Generated distinct IDs: 1000 and 1001

Diagnostic Output When assert_ne! Fails

When left != right evaluates to false, assert_ne! halts execution and prints both colliding values:

fn main() {
    let primary_port = 8080_u16;
    let metrics_port = 8080_u16;

    assert_ne!(
        primary_port, metrics_port,
        "primary and metrics servers cannot bind to the same port"
    );
}
thread 'main' panicked at src/main.rs:5:5:
assertion `left != right` failed: primary and metrics servers cannot bind to the same port
  left: 8080
 right: 8080