简体   繁体   English

如何在不重复的情况下以相同的方式为多种类型实现特征?

[英]How to implement a trait in the same way for many types without repetition?

Given a trait, we may want to implement it for many types. 鉴于一个特征,我们可能希望为许多类型实现它。

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 } }

What's an idiomatic way to avoid writing out functions for each type? 避免为每种类型写出函数的惯用方法是什么? Should I use default implementations, or maybe macros? 我应该使用默认实现,还是宏?

I am aware of the num crate for these specific methods, but I'm interested to know how to do this in the general case. 我知道的num箱子为这些特定的方法,但我想知道如何在一般情况下做到这一点。

As per Rust reference : 根据Rust参考

An implementation is an item that implements a trait for a specific type. 实现是实现特定类型的特征的项。

Take a look at the implementations of Zero and One in the docs (deprecated since Rust 1.11, I removed the deprecation attributes for brevity): 看一下文档ZeroOne的实现(自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 }

If the standard docs did it with macros, I doubt a better way exists. 如果标准文档用宏做了,我怀疑是否存在更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM