TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
<<= (left shift assignment) operator performs a bitwise left shift on the left operand by the number of bit positions specified by the right operand, mutating the left operand in place. Unlike some languages where compound assignment is syntactic sugar for x = x << y, Rust treats <<= as a distinct operation that desugars directly to a method call on the std::ops::ShlAssign trait.
Mechanics
- Bit Manipulation: The binary representation of the
left_operandis shifted to the left. The vacated least significant bits (LSBs) are filled with zeros. The most significant bits (MSBs) shifted beyond the bit-width of the data type are discarded. - Mutability: The
left_operandmust be declared as mutable (mut) because the operation modifies the value in place. - Type Flexibility: For standard library primitive types, both operands must be integers, but they do not need to be the same integer type (e.g., shifting a
u64by au8is valid). For custom types, the operands can be of any type, provided theShlAssigntrait is implemented for that specific type combination.
Trait Implementation
The<<= operator is powered by the std::ops::ShlAssign trait.
x <<= y strictly desugars to ShlAssign::shl_assign(&mut x, y). This is completely independent of the Shl trait used for the standard << operator. Implementing ShlAssign on custom structs or enums defines their behavior for the <<= operator.
Overflow Behavior
Rust enforces strict rules regarding the shift amount (the right operand) to prevent undefined behavior when shifting by an amount greater than or equal to the bit-width of the left operand:- Debug Profile: If the right operand is greater than or equal to the total number of bits in the left operand’s type (e.g., shifting a
u8by 8 or more), the program panics at runtime. - Release Profile: The compiler performs a masked shift. The right operand is masked using a bitwise AND operation with
N - 1, whereNis the bit-width of the left operand’s type. For example, shifting au8(whereN = 8, soN - 1 = 7) by 9 in release mode results in an actual shift of 1 (9 & 7).
Syntax Visualization
Master Rust with Deep Grasping Methodology!Learn More





