如何在Rust中计算u64模数u8?

时间:2019-07-08 13:33:06

标签: rust type-conversion integer mod

我想编写一个简单的Rust函数,该函数以u64为模的u8并返回u8

fn bucket(value: u64, number_of_buckets: u8) -> u8 {
    value % number_of_buckets
}

但是,由于类型不匹配而无法编译:

error[E0308]: mismatched types
 --> src/lib.rs:2:13
  |
2 |     value % number_of_buckets
  |             ^^^^^^^^^^^^^^^^^ expected u64, found u8

error[E0308]: mismatched types
 --> src/lib.rs:2:5
  |
1 | fn bucket(value: u64, number_of_buckets: u8) -> u8 {
  |                                                 -- expected `u8` because of return type
2 |     value % number_of_buckets
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found u64
help: you can convert an `u64` to `u8` and panic if the converted value wouldn't fit
  |
2 |     (value % number_of_buckets).try_into().unwrap()
  |

error[E0277]: cannot mod `u64` by `u8`
 --> src/lib.rs:2:11
  |
2 |     value % number_of_buckets
  |           ^ no implementation for `u64 % u8`
  |
  = help: the trait `std::ops::Rem<u8>` is not implemented for `u64`

要解决此问题,我必须编写以下非常丑陋的代码:

use std::convert::TryInto;

fn bucket(value: u64, number_of_buckets: u8) -> u8 {
    (value % number_of_buckets as u64).try_into().unwrap()
}

没有两次显式的类型转换和两次函数调用,没有更简单的方法吗?我有两个人为这么简单的东西写了那么多代码,这一事实使我怀疑我缺少明显的东西。

0 个答案:

没有答案
相关问题