Ben Chuanlong Du's Blog

It is never too late to learn.

The Modulus Operator in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. The modulus operator (%) in Rust is very picky about data types. It is only defined for two integers with the same type.

  2. The modulus operation involves division is much slower compared to multiplication. You should avoid using modulus unless you absolutely need it. If you use modulus as simple hashing function, please refer to Fast Hashing Algorithms for faster alternaitves.

In [2]:
8 % 5
Out[2]:
3
In [3]:
let x: u64 = 10;
let y: u32 = 6;
x % y
x % y
    ^ expected `u64`, found `u32`
mismatched types
x % y
  ^ no implementation for `u64 % u32`
cannot mod `u64` by `u32`
help: the trait `Rem<u32>` is not implemented for `u64`
In [4]:
let x: u64 = 10;
let y: u32 = 6;
x % (y as u64)
Out[4]:
4

Comments