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 compound assignment operator for the remainder operation. It computes the remainder of the division of the left operand by the right operand and assigns the resulting value directly back to the left operand in place. Mechanically, it is syntactic sugar that combines the modulo operator (%) with the assignment operator (=).
// Syntax
left_operand %= right_operand;

// Semantically equivalent to
left_operand = left_operand % right_operand;

Trait Implementation

Under the hood, the %= operator is powered by the std::ops::RemAssign trait. To use %= on custom types, you must implement this trait for the left-hand side (LHS) type.
pub trait RemAssign<Rhs = Self> {
    fn rem_assign(&mut self, rhs: Rhs);
}
Because the trait method takes &mut self, the left operand must always be declared as mutable. The right-hand side (RHS) is consumed by the operation unless it implements Copy or is passed by reference (depending on the specific trait implementation).

Technical Behavior and Rules

  • Mutability: The variable on the left side of the operator must be bound with mut.
  • Sign Semantics: Rust uses truncated division for integers. Consequently, the remainder inherits the sign of the dividend (the left operand).
  • Floating-Point Support: Unlike some languages where modulo is strictly an integer operation, Rust implements RemAssign for floating-point types (f32, f64).
  • Panic Conditions:
    • Division by Zero: Executing a %= 0 will trigger a runtime panic.
    • Overflow: Executing a %= -1 where a is the minimum representable value for a signed integer type (e.g., i32::MIN %= -1) will panic due to integer overflow.

Syntax Visualization

// Integer remainder
let mut x: i32 = 17;
x %= 5; 
// x is now 2

// Floating-point remainder
let mut y: f64 = 5.5;
y %= 2.0; 
// y is now 1.5

// Sign inheritance (matches the left operand)
let mut z: i32 = -10;
z %= 3; 
// z is now -1
Master Rust with Deep Grasping Methodology!Learn More