Is there a modulus (not remainder) function / operation?

前端 未结 4 2020
粉色の甜心
粉色の甜心 2020-12-14 05:31

In Rust (like most programming languages), the % operator performs the remainder operation, not the modulus operation. These operations have d

4条回答
  •  青春惊慌失措
    2020-12-14 05:57

    No, Rust doesn't have a built in modulus, see this discussion for some reasons why.

    Here's an example that might be handy:

    ///
    /// Modulo that handles negative numbers, works the same as Python's `%`.
    ///
    /// eg: `(a + b).modulo(c)`
    ///
    pub trait ModuloSignedExt {
        fn modulo(&self, n: Self) -> Self;
    }
    macro_rules! modulo_signed_ext_impl {
        ($($t:ty)*) => ($(
            impl ModuloSignedExt for $t {
                #[inline]
                fn modulo(&self, n: Self) -> Self {
                    (self % n + n) % n
                }
            }
        )*)
    }
    modulo_signed_ext_impl! { i8 i16 i32 i64 }
    

提交回复
热议问题