Skip to main content
The ^ operator in Rust performs a bitwise Exclusive OR (XOR) operation on integer types and a logical XOR operation on boolean types. It evaluates the operands bit-by-bit, returning 1 (or true) if the corresponding bits differ, and 0 (or false) if they are identical.

Evaluation Logic (Truth Table)

For any given bit position in the operands, the ^ operator applies the following logic:

Integer Bitwise XOR

When applied to integers (u8, i32, usize, etc.), Rust aligns the binary representations of both operands and applies the XOR logic to each corresponding bit. Both operands must be of the exact same type.

Boolean Logical XOR

When applied to bool types, ^ acts as a strict logical inequality operator. It returns true only if exactly one of the operands is true. Unlike || or &&, the ^ operator does not short-circuit; it always evaluates both operands.

Trait Implementations

Under the hood, the ^ operator is syntactic sugar for the std::ops::BitXor trait.
Custom types can support the ^ operator by implementing this trait.

Compound Assignment (^=)

Rust also provides the ^= operator, which performs the XOR operation and assigns the result back to the left-hand operand in a single step. This requires the left-hand variable to be mutable and relies on the std::ops::BitXorAssign trait.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More