我对C++很有经验,并开始try 使用Ruust.
在try 实现一些简单的泛型函数时,我遇到了以下问题:
use std::ops::BitAnd;
use std::cmp::Eq;
fn is_odd_i32(x: u32) -> bool {
if x & 1_u32 == 1_u32 { true } else { false }
}
fn is_odd<T: BitAnd + Eq>(x: &T) -> bool {
if (*x & (1 as T)) == (1 as T) { true } else { false }
}
fn main() {
println!("is_odd -> '{}'", is_odd(&23_u64));
println!("is_odd -> '{}'", is_odd(&23_u32));
}
问题似乎是将按位AND结果与0或1进行比较.我知道要实现这一点,1(或0)必须可以转换为类型T,但不知道如何实现.我也试了T::try_from(1_u8).ok().unwrap()
次,但这也不起作用.
我不知道该怎么解决这个问题.
我收到的错误是:
error[E0369]: binary operation `==` cannot be applied to type `<T as BitAnd>::Output`
--> src/main.rs:27:24
|
27 | if (*x & (1 as T)) == (1 as T) { true } else { false }
| --------------- ^^ -------- T
| |
| <T as BitAnd>::Output
|
help: consider further restricting the associated type
|
26 | fn is_odd<T: BitAnd + Eq>(x: &T) -> bool where <T as BitAnd>::Output: PartialEq<T> {
| +++++++++++++++++++++++++++++++++++++++++
error[E0605]: non-primitive cast: `{integer}` as `T`
--> src/main.rs:27:14
|
27 | if (*x & (1 as T)) == (1 as T) { true } else { false }
| ^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
error[E0605]: non-primitive cast: `{integer}` as `T`
--> src/main.rs:27:27
|
27 | if (*x & (1 as T)) == (1 as T) { true } else { false }
| ^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
顺便说一句,我只是在玩弄特征和泛型,这不是测试整数是否奇数的最好方法.