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 right shift assignment operator. It shifts the binary representation of the left operand to the right by the number of bits specified by the right operand, and assigns the resulting value back to the left operand in place.

Syntax and Desugaring

The expression x >>= y requires the left operand to be mutable. In Rust, compound assignment operators do not desugar to their expanded assignment forms (i.e., x = x >> y). Instead, x >>= y desugars directly to a mutable borrow and a method call on the std::ops::ShrAssign trait: ShrAssign::shr_assign(&mut x, y).
let mut x: u8 = 16; // Binary: 0001_0000
x >>= 2;            // Binary: 0000_0100 (Decimal: 4)

Type-Dependent Behavior

The behavior of the right shift operation depends strictly on the signedness of the left operand’s type:
  1. Unsigned Integers (u8, u16, u32, u64, u128, usize): Performs a logical right shift. The bits are shifted to the right, and the newly vacated most significant bits (MSB) are filled with zeros.
let mut x: u8 = 0b1111_0000; // 240 x >>= 2; // 0b0011_1100 (60)
2. **Signed Integers (`i8`, `i16`, `i32`, `i64`, `i128`, `isize`)**: 

   Performs an **arithmetic right shift**. The bits are shifted to the right, but the newly vacated MSBs are filled with copies of the original sign bit (sign extension). This preserves the negative or positive sign of the two's complement integer.
   ```rust
let mut x: i8 = -16; // 0b1111_0000
x >>= 2;             // 0b1111_1100 (-4)

Trait Implementation

The >>= operator is backed by the std::ops::ShrAssign trait.
pub trait ShrAssign<Rhs = Self> {
    fn shr_assign(&mut self, rhs: Rhs);
}
Because the right-hand side (Rhs) is a generic parameter, the shift amount does not need to be the same type as the value being shifted. Rust’s standard library implements ShrAssign for all combinations of primitive integer types.
let mut value: u32 = 100;
let shift_amount: u8 = 2;
value >>= shift_amount; // Valid: Rhs is u8, Self is u32

Overflow Behavior

If the right operand (the shift amount) is greater than or equal to the number of bits in the left operand’s type, the behavior depends on the compilation profile. In safe Rust, shifting by an amount greater than or equal to the type’s bit-width is never undefined behavior.
  • Debug mode: The operation panics. This panic exists strictly to catch programmer logic errors (integer overflow).
  • Release mode: The shift amount is masked (modulo the bit-width of the type) before the shift is applied. For example, shifting a u8 (which has an 8-bit width) by 9 bits will actually shift by 9 % 8 = 1 bit.
Master Rust with Deep Grasping Methodology!Learn More