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 is the bitwise XOR (exclusive OR) assignment operator. It evaluates the bitwise XOR between a mutable left-hand operand and a right-hand operand, assigning the computed result directly back to the left-hand operand in place.
let mut a = 5;
let b = 3;

a ^= b; 

Underlying Trait and Desugaring

In Rust, compound assignment operators do not desugar to their expanded assignment equivalents. The expression a ^= b is not syntactic sugar for a = a ^ b. Evaluating a = a ^ b would invoke the BitXor::bitxor(a, b) trait method, which takes the left operand by value and could cause a move if the type does not implement Copy. Instead, ^= is a distinct operation powered by the std::ops::BitXorAssign trait:
pub trait BitXorAssign<Rhs = Self> {
    fn bitxor_assign(&mut self, rhs: Rhs);
}
When a ^= b is invoked, the compiler desugars the operation directly into a method call that takes the left operand by mutable reference:
BitXorAssign::bitxor_assign(&mut a, b);
The Rust standard library implements this trait for all primitive integer types and booleans.

Type-Specific Mechanics

1. Integer Types (u8, i32, usize, etc.) When applied to integers, the operator performs a parallel, bit-by-bit comparison of the binary representations of both operands. For each bit position:
  • If the bits are different (1 and 0, or 0 and 1), the resulting bit is 1.
  • If the bits are identical (1 and 1, or 0 and 0), the resulting bit is 0.
let mut x: u8 = 0b1010_1100; // Decimal: 172
let y: u8     = 0b0110_0101; // Decimal: 101

x ^= y; 

// Calculation:
//   1010_1100
// ^ 0110_0101
// --------
//   1100_1001 (Decimal: 201)
2. Boolean Types (bool) When applied to bool primitives, ^= acts as a strict logical inequality assignment. The left-hand operand evaluates to true if the operands possess different truth values, and false if they share the same truth value.
let mut state = true;

state ^= false; // state is true  (true ^ false = true)
state ^= true;  // state is false (true ^ true = false)
state ^= false; // state is false (false ^ false = false)

Mutability and Evaluation

Because ^= mutates the left-hand operand in place, the variable must be bound with the mut keyword. Furthermore, unlike logical operators (&&, ||), bitwise operators do not short-circuit. Both the left and right operands are fully evaluated before the XOR assignment occurs.
Master Rust with Deep Grasping Methodology!Learn More