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 -= (subtraction assignment) operator is a compound assignment operator that subtracts the right-hand operand from the left-hand operand, mutating the left-hand operand in place with the resulting value. Syntax and Desugaring In Rust, -= is syntactic sugar for the sub_assign method. When the compiler encounters this operator, it translates the operation into a method call.
let mut x = 10;
x -= 4; 

// The compiler desugars the above into:
std::ops::SubAssign::sub_assign(&mut x, 4);
Underlying Trait The mechanics of -= are defined by the std::ops::SubAssign trait. To use -= with custom types, you must implement this trait for the left-hand type.
pub trait SubAssign<Rhs = Self> {
    fn sub_assign(&mut self, rhs: Rhs);
}
Technical Characteristics
  • Mutability Requirement: The left-hand operand must be explicitly bound with mut. The trait signature requires an exclusive, mutable reference (&mut self) to modify the memory location in place.
  • Return Type: Unlike C or C++, where assignment operators evaluate to the assigned value, the -= expression in Rust evaluates to the unit type (). This strictly prevents assignment chaining. For example, let a: i32 = b -= c; will result in a type error, while let a = b -= c; compiles successfully but infers the type of a as () rather than a numerical value.
  • Ownership and Borrowing: The right-hand operand (Rhs) is passed by value. For non-Copy types, this consumes the right-hand operand. However, SubAssign can be implemented where Rhs is a reference (e.g., impl SubAssign<&T> for T), allowing the right-hand operand to be borrowed rather than consumed.
  • Overflow Behavior: When applied to primitive integer types, -= is subject to Rust’s standard integer overflow rules. An underflow will cause a panic in debug profiles and perform two’s complement wrapping in release profiles.
Master Rust with Deep Grasping Methodology!Learn More