[英]Rust trait bounds for integral types
Suppose I have my own type as a tuple struct假设我有自己的类型作为元组结构
struct MyType(u8);
And would like to implement the From
trait for the other integral types in a generic way, like并希望以通用方式为其他整数类型实现From
特征,例如
impl From<T> for MyType {
fn from(num: T) -> Self {
MyType((num & 0xff) as u8)
}
}
Rust does not allow this because generic types T
do not have the as
operator. Rust 不允许这样做,因为泛型类型T
没有as
运算符。 How can I constrain T
to the integral types so that as
can be used?我怎么能限制T
的整数类型,以便as
可以用吗? something along the lines of类似的东西
impl From<T: Integral> for MyType {...}
You can use the num-traits
crate.您可以使用num-traits
板条箱。
PrimInt
is the relevant trait, which extends NumCast
which allows conversion between the primitive numeric types. PrimInt
是相关的 trait,它扩展了NumCast
,它允许原始数字类型之间的转换。
EDIT: Here's an example implementation.编辑:这是一个示例实现。 It's a bit ugly because many of the relevant conversions return Option
, since they don't know ahead of time that the values are in range.这有点难看,因为许多相关的转换都返回Option
,因为它们提前不知道这些值在范围内。
impl<T: PrimInt> From<T> for MyType {
fn from(num: T) -> Self {
let clamped = num & T::from(0xFFu8).unwrap();
Self(clamped.to_u8().unwrap())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.