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 OR assignment operator. It performs a bitwise OR operation between a mutable left-hand operand and a right-hand operand, assigning the resulting value directly back to the left-hand operand. Mechanically, a |= b serves as syntactic sugar for a = a | b, with the strict requirement that the left-hand variable must be declared as mutable (mut).
let mut lhs: u8 = 0b1010_0000;
let rhs: u8     = 0b0000_1111;

lhs |= rhs; 
// lhs is now 0b1010_1111

Underlying Trait Implementation

In Rust’s type system, the |= operator is powered by the std::ops::BitOrAssign trait. When the compiler encounters a |= b, it translates the expression into a method call: a.bitor_assign(b).
pub trait BitOrAssign<Rhs = Self> {
    fn bitor_assign(&mut self, rhs: Rhs);
}
To use |= with custom data structures, you must implement this trait for your type. The method takes an exclusive, mutable reference to self (&mut self) and consumes the rhs operand.

Type Behavior

The operator exhibits specific behaviors depending on the primitive types involved:
  • Integers (u8, i32, usize, etc.): Performs a standard bit-level OR operation. Each bit in the result is 1 if the corresponding bit in either the LHS or RHS is 1. Both operands must be of the exact same integer type; Rust does not implicitly coerce types during bitwise assignment.
  • Booleans (bool): Performs a strict logical OR operation.

Evaluation Semantics

A critical mechanical distinction of |= when applied to booleans is the absence of short-circuit evaluation. Unlike the standard logical OR operator (||), which halts evaluation if the LHS is true, the |= operator strictly evaluates both the LHS and RHS expressions before executing the assignment.
let mut flag = true;

// `expensive_computation()` WILL execute and be evaluated, 
// even though `flag` is already true.
flag |= expensive_computation(); 
Master Rust with Deep Grasping Methodology!Learn More