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 *= (multiplication assignment) operator is a compound assignment operator that multiplies a mutable left-hand operand by a right-hand operand, storing the resulting product directly in the left-hand operand.

Syntax and Desugaring

let mut x = 5;
x *= 3; // x is mutated in-place to 15
At the compiler level, *= is syntactic sugar for the mul_assign method defined in the std::ops::MulAssign trait. When the Rust compiler encounters LHS *= RHS, it desugars the expression into a method call:
LHS.mul_assign(RHS);

Trait Definition

The underlying trait is defined in the standard library as follows:
pub trait MulAssign<Rhs = Self> {
    fn mul_assign(&mut self, rhs: Rhs);
}

Technical Mechanics

  • Mutability Requirement: The left-hand side (LHS) must be explicitly bound with mut. Because mul_assign takes &mut self, the operator requires an exclusive, mutable borrow of the LHS.
  • Type Resolution: The types of the LHS and RHS do not strictly need to be identical, provided the LHS type implements MulAssign<RHS>. For example, standard library primitives implement MulAssign for their own types (e.g., i32 *= i32), but custom types can implement MulAssign to accept disparate RHS types.
  • Ownership: The RHS operand is passed by value. If the RHS type does not implement Copy, it will be consumed (moved) by the *= operation, unless the trait is explicitly implemented to accept a reference (e.g., MulAssign<&T>).
  • Return Type: The *= expression evaluates to the unit type (). It cannot be chained like in C or C++ (e.g., a = b *= c is invalid in Rust because b *= c returns ()).
  • Overflow Behavior: For primitive integer types, *= adheres to Rust’s standard arithmetic overflow rules. It will trigger a panic in debug profiles if the multiplication exceeds the type’s bounds, and it will perform two’s complement wrapping in release profiles. Floating-point types (f32, f64) will yield inf or -inf upon overflow, adhering to IEEE 754 standards.
Master Rust with Deep Grasping Methodology!Learn More