Skip to main content
The /= operator is the compound division assignment operator. It divides a mutable left-hand operand by a right-hand operand and assigns the quotient back to the left-hand operand. Unlike in C or C++, Rust does not desugar a /= b to a = a / b. Instead, it desugars directly to a method call on the std::ops::DivAssign trait: DivAssign::div_assign(&mut a, b).

Trait Implementation

The /= operator is strictly powered by the DivAssign trait. If a custom type implements the Div trait but omits DivAssign, attempting to use /= will result in a compilation error; the compiler will not automatically fall back to a = a / b.
Because div_assign takes &mut self, the left-hand operand must be a mutable place expression. This can be a variable declared with the mut keyword, or a dereferenced mutable reference (e.g., *x /= 2 where x is &mut i32). The operation modifies the left operand in place rather than allocating a new value, provided the type’s implementation is optimized to do so.

Execution Mechanics

The behavior of /= depends strictly on the types of the operands: Integer Types (i32, u64, etc.)
  • Truncation: Integer division truncates the result towards zero. There is no rounding.
  • Division by Zero: Attempting to divide an integer by zero (e.g., x /= 0) will trigger a runtime panic!.
  • Overflow: Dividing the minimum representable value of a signed integer by -1 causes an arithmetic overflow. For example, if x is i8::MIN, executing x /= -1 is considered a hard error and will always panic at runtime in both debug and release profiles.
Floating-Point Types (f32, f64)
  • IEEE 754 Semantics: Floating-point division adheres strictly to the IEEE 754 standard.
  • Division by Zero: Dividing a non-zero float by zero does not panic. If x is 5.0, executing x /= 0.0 mutates x to Infinity (inf) or -Infinity (-inf) depending on the sign.
  • NaN: Dividing zero by zero, such as x /= 0.0 where x is 0.0, mutates the left operand to NaN (Not a Number).

Syntax Visualization

Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More