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.
>> operator is the bitwise right shift operator. It shifts the binary representation of the left-hand operand to the right by the number of bit positions specified by the right-hand operand.
Shift Mechanics: Logical vs. Arithmetic
The behavior of the>> operator depends strictly on the type of the left-hand operand:
- Unsigned Integers (
u8,u16,u32,u64,u128,usize): Performs a logical right shift. The bits are shifted right, and the vacated most significant bits (MSBs) on the left are filled with zeros (0). - Signed Integers (
i8,i16,i32,i64,i128,isize): Performs an arithmetic right shift. The bits are shifted right, and the vacated MSBs are filled with the original sign bit (sign extension). This preserves the sign of the two’s complement negative number.
Trait Implementation
The>> operator is syntactic sugar for the std::ops::Shr trait. The compound assignment operator >>= is backed by the std::ops::ShrAssign trait.
Rhs) does not need to be the same type as the left-hand operand. The standard library implements Shr for all combinations of integer types (e.g., shifting a u64 by a u8 is perfectly valid).
Overflow and Panic Behavior
The>> operator enforces strict rules regarding the validity of the right-hand operand to prevent undefined behavior:
- Negative Shift Amounts: Because
Shraccepts signed integers for the right-hand operand, passing a negative value (e.g.,val >> -1_i32) is syntactically valid but will unconditionally panic at runtime in both Debug and Release modes. - Compile-time Out-of-Bounds: Hardcoding a shift amount greater than or equal to the total number of bits in the left operand’s type (e.g., shifting a
u32by32) triggers anarithmetic_overflowcompiler error. - Runtime Out-of-Bounds (Debug mode): Shifting by a value greater than or equal to the bit-width of the left operand triggers a panic.
- Runtime Out-of-Bounds (Release mode): Performs a masked shift. The right operand is masked to the bit-width of the left operand minus one (e.g.,
val >> (shift & 31)for au32).
Explicit Shift Methods
To bypass default operator behavior and explicitly control out-of-bounds shifts, Rust provides explicit methods on integer primitives. Unlike the>> operator, these methods strictly require a u32 for the right-hand operand. Attempting to pass a negative value to these methods results in a compile-time type mismatch error rather than a runtime panic.
checked_shr(n: u32): ReturnsNoneifnis greater than or equal to the bit-width of the left operand.wrapping_shr(n: u32): Explicitly performs the masked shift regardless of the compilation profile.overflowing_shr(n: u32): Returns a tuple(result, bool)where the boolean indicates if the shift amountnwas out of bounds.
Master Rust with Deep Grasping Methodology!Learn More





