Rust currently has a remainder operator in the form of %
, which behaves as the operator of the same symbol does in languages like C or Java. It is also similar to the modulo operator found in languages such as Python or Haskell, except for its behaviour for negative arguments – remainder is based on truncating division, whereas modulo is based on flooring division.
In the vast majority of cases whilst programming (see http://dl.acm.org/citation.cfm?doid=128861.128862), the behaviour of the modulo operator is more useful than that of the remainder operator. Therefore, it would be useful to add a modulo operator to the language.
This issue has been discussed before: https://mail.mozilla.org/pipermail/rust-dev/2013-April/003680.html, as well as having been brought up in various other places (https://github.com/rust-lang/rust/issues/13909, https://stackoverflow.com/questions/31210357/is-there-a-modulus-not-remainder-function-operation, https://users.rust-lang.org/t/proper-modulo-support/903, https://www.reddit.com/r/rust/comments/3yoo1q/remainder/, etc.), but although the general consensus seems to be that having an operator for modulo (in addition to the remainder operator) would be very useful: as it is, there is no operator or standard library method to achieve this.
As no progress seems to have been made on this issue for a while now, I’d like to make an RFC to add a new operator, %%
(bike-shedding aside: alternatives like mod
are also fine, but I think having an operator as opposed to just a method is very helpful) that implements this functionality. Below is a snippet showing some of the differences between the two operations:
// Remainder operator (%)
5 % 3 // 2
5 % -3 // 2
-5 % 3 // -2
-5 % -3 // -2
// Modulo operator (%%)
5 %% 3 // 2
5 %% -3 // -1
-5 %% 3 // 1
-5 %% -3 // -2
It may also be helpful to define a flooring division operator \
, which forms a pair with modulo, as /
is paired with %
, so that just as (a / b) * b + (a % b) == a
, we have: (a \ b) * b + (a %% b) == a
. (The syntax is unimportant for now.)
Is an RFC the right place to start? What details are important to clarify in such an RFC?