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 <<= (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.
left_operand <<= right_operand;

Mechanics

  • Bit Manipulation: The binary representation of the left_operand is 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_operand must 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 u64 by a u8 is valid). For custom types, the operands can be of any type, provided the ShlAssign trait is implemented for that specific type combination.

Trait Implementation

The <<= operator is powered by the std::ops::ShlAssign trait.
pub trait ShlAssign<Rhs = Self> {
    fn shl_assign(&mut self, rhs: Rhs);
}
Evaluating 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 u8 by 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, where N is the bit-width of the left operand’s type. For example, shifting a u8 (where N = 8, so N - 1 = 7) by 9 in release mode results in an actual shift of 1 (9 & 7).

Syntax Visualization

// 0b0000_0011 represents decimal 3
let mut value: u8 = 0b0000_0011; 

// Shift bits left by 3 positions
value <<= 3; 

// The bits are shifted, and vacated LSBs are filled with 0s.
// value is now 0b0001_1000 (decimal 24)
assert_eq!(value, 24);
Master Rust with Deep Grasping Methodology!Learn More