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 in Rust computes the remainder of a division operation. Strictly defined, it is a truncating remainder operator rather than a mathematical modulo operator, meaning the sign of the result always matches the sign of the dividend (the left-hand operand). Under the hood, the % operator is syntactic sugar for the std::ops::Rem trait.
pub trait Rem<Rhs = Self> {
    type Output;
    fn rem(self, rhs: Rhs) -> Self::Output;
}

Integer Mechanics and Signage

For integer types, the operation satisfies the equation (a / b) * b + (a % b) == a. Because Rust’s integer division (/) truncates towards zero, the remainder must carry the sign of the left operand to satisfy this equation.
let a =  10 %  3; //  1
let b = -10 %  3; // -1
let c =  10 % -3; //  1
let d = -10 % -3; // -1
If you require a mathematical modulo where the result is strictly non-negative, you must use the rem_euclid method instead of the % operator. This method computes the Euclidean remainder, which guarantees the result is always non-negative (0 <= r < |divisor|), regardless of whether the divisor is positive or negative.
let r1 = (-10_i32).rem_euclid(3);  // 2
let r2 = (-10_i32).rem_euclid(-3); // 2

Floating-Point Mechanics

The % operator is natively implemented for floating-point primitives (f32 and f64). It computes the floating-point remainder matching the same truncating logic used for integers. In accordance with IEEE 754 standards, floating-point remainder by zero does not trigger a panic. Instead, evaluating x % 0.0 results in NaN (Not a Number).
let f1 = 5.5_f64 % 2.0_f64;  //  1.5
let f2 = -5.5_f64 % 2.0_f64; // -1.5
let f3 = 5.5_f64 % 0.0_f64;  //  NaN

Panic and Overflow Conditions

The % operator exhibits specific behaviors for invalid integer operations:
  1. Integer Division by Zero: Evaluating x % 0 for any integer type triggers a runtime panic unconditionally, in both debug and release profiles.
  2. Signed Integer Overflow: Evaluating T::MIN % -1 for any signed integer type T (e.g., i32::MIN % -1) triggers a runtime panic unconditionally in all compilation profiles, yielding an “attempt to calculate the remainder with overflow” error. This occurs because the underlying hardware division instructions (such as idiv on x86 architectures) compute both the quotient and remainder simultaneously, and the quotient T::MIN / -1 overflows the capacity of two’s complement representation. To safely compute this remainder without panicking, developers must use the overflowing_rem method.

Compound Assignment

Rust provides the %= operator for in-place remainder assignment. This mutates the left-hand operand and is backed by the std::ops::RemAssign trait.
let mut x = 10;
x %= 3; // x is now 1
Master Rust with Deep Grasping Methodology!Learn More