[英]How to implement a trait in the same way for many types without repetition?
鉴于一个特征,我们可能希望为许多类型实现它。
pub trait RTypeUnit {
fn zero() -> Self;
fn one() -> Self;
}
impl RTypeUnit for usize { fn zero() -> usize { 0 } fn one() -> usize { 1 } }
impl RTypeUnit for isize { fn zero() -> isize { 0 } fn one() -> isize { 1 } }
impl RTypeUnit for u64 { fn zero() -> u64 { 0 } fn one() -> u64 { 1 } }
impl RTypeUnit for i64 { fn zero() -> i64 { 0 } fn one() -> i64 { 1 } }
impl RTypeUnit for u32 { fn zero() -> u32 { 0 } fn one() -> u32 { 1 } }
impl RTypeUnit for i32 { fn zero() -> i32 { 0 } fn one() -> i32 { 1 } }
impl RTypeUnit for u16 { fn zero() -> u16 { 0 } fn one() -> u16 { 1 } }
impl RTypeUnit for i16 { fn zero() -> i16 { 0 } fn one() -> i16 { 1 } }
impl RTypeUnit for u8 { fn zero() -> u8 { 0 } fn one() -> u8 { 1 } }
impl RTypeUnit for i8 { fn zero() -> i8 { 0 } fn one() -> i8 { 1 } }
避免为每种类型写出函数的惯用方法是什么? 我应该使用默认实现,还是宏?
我知道的num
箱子为这些特定的方法,但我想知道如何在一般情况下做到这一点。
根据Rust参考 :
实现是实现特定类型的特征的项。
看一下文档中Zero
和One
的实现(自Rust 1.11以来不推荐使用,为简洁起见,我删除了弃用属性):
pub trait Zero: Sized {
fn zero() -> Self;
}
pub trait One: Sized {
fn one() -> Self;
}
macro_rules! zero_one_impl {
($($t:ty)*) => ($(
impl Zero for $t {
#[inline]
fn zero() -> Self { 0 }
}
impl One for $t {
#[inline]
fn one() -> Self { 1 }
}
)*)
}
zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
如果标准文档用宏做了,我怀疑是否存在更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.