Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
Operand AOperand BResult (A ^ B)
0 / false0 / false0 / false
0 / false1 / true1 / true
1 / true0 / false1 / true
1 / true1 / true0 / false

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.
let a: u8 = 0b1010_1100;
let b: u8 = 0b0110_0101;

let result = a ^ b;

// Evaluation breakdown:
//   1010_1100 (a)
// ^ 0110_0101 (b)
// --------
//   1100_1001 (result)

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.
let val1 = true ^ false; // true
let val2 = true ^ true;  // false
let val3 = false ^ false; // false

Trait Implementations

Under the hood, the ^ operator is syntactic sugar for the std::ops::BitXor trait.
pub trait BitXor<Rhs = Self> {
    type Output;
    fn bitxor(self, rhs: Rhs) -> Self::Output;
}
Custom types can support the ^ operator by implementing this trait.
use std::ops::BitXor;

struct Flags(u8);

impl BitXor for Flags {
    type Output = Self;

    fn bitxor(self, rhs: Self) -> Self::Output {
        Flags(self.0 ^ rhs.0)
    }
}

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.
let mut x: u8 = 0b1111_0000;
x ^= 0b1010_1010;

// x is now 0b0101_1010
Master Rust with Deep Grasping Methodology!Learn More