R
RUSTY YELLOW PAGES

!=Operator


Explanation

!= tests inequality — the negation of ==. It's provided automatically by std::cmp::PartialEq (a single trait supplies both eq and, by default, ne as !self.eq(other)); a type essentially never needs to implement != separately from ==.

Usage examples

Testing for inequality

let state = 3;
let ready = state != 0; // <- `!=` tests for inequality

Validating input

A guard clause that rejects a sentinel or placeholder value reads more directly with != than with a negated ==, and is a common first line of defense before an input is used.

fn set_channel(channel: u8) -> Result<(), &'static str> {
    if channel != 0 { // <- `!=` guards against the reserved "unset" sentinel
        Ok(())
    } else {
        Err("channel 0 is reserved and cannot be assigned")
    }
}

assert!(set_channel(0).is_err());
assert!(set_channel(4).is_ok());

channel != 0 reads as "channel is set" more directly than !(channel == 0), and the compiler treats them identically since != is PartialEq::ne, not a separate check — see == for the fuller treatment of the underlying trait and its derive/impl tradeoffs.

Explanation

Embedded support: Full

!= means exactly the same thing under #![no_std] — still PartialEq::ne via core::cmp, no different from =='s embedded story. The concrete case that comes up constantly in firmware is polling a status register's busy bit until it clears, or flagging a hardware ID read-back that doesn't match what a driver expects — both are != comparisons against a bit pattern the datasheet defines, checked in a tight loop rather than once at startup.

Usage examples

Detecting an unexpected device on the bus

const EXPECTED_CHIP_ID: u8 = 0xD4;

fn is_unexpected_chip(chip_id_reg: u8) -> bool {
    chip_id_reg != EXPECTED_CHIP_ID // <- `!=` flags any chip ID that doesn't match what this driver expects
}

Polling a busy bit until it clears

const BUSY_BIT: u8 = 0x80;

fn wait_until_ready(read_status: impl Fn() -> u8) {
    while read_status() & BUSY_BIT != 0 { // <- `!=` keeps polling until the busy bit clears
        // spin until the peripheral reports it's no longer busy
    }
}