我想强制执行泛型类型的基本类型,以使以下代码有效:
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
fn method(&self) -> u32 {
self.value as u32
}
}
fn main() {
let wrapper = Wrapper { value: 10 as u16 };
println!("{}", wrapper.method());
}
此问题类似于Is there a trait for only primitive types that I can use in a generic function?,除此之外我们可以根据类型推断转换是否成功。
编译器建议使用From
特征:
error[E0605]: non-primitive cast: `T` as `u32`
--> src/main.rs:7:9
|
7 | self.value as u32
| ^^^^^^^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
这可以归结为为每种原始类型实现From
,对吧?有解决方法吗?
当我尝试为原始类型实现一个位迭代器时,我遇到了这个问题:
struct BitIterator<T> {
value: T,
pos: usize,
}
impl<T> BitIterator<T> {
fn new(value: T) -> BitIterator<T> {
//Accept up 32 bit for now
assert!(std::mem::size_of::<T>() <= 4);
BitIterator { value, pos: 0 }
}
}
impl<T> Iterator for BitIterator<T> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.pos >= std::mem::size_of::<T>() * 8 {
return None;
}
let res = Some((self.value as u32 >> self.pos) & 1);
self.pos += 1;
res
}
}