< 返回版块

minstrel1977 发表于 2020-05-14 17:04

Tags:rust,trait,impl

trait Comparable {
    fn compare(&self, object: &Self) -> i8;
}

impl<T> Comparable for T where T: f64,i32
{
    fn compare(&self, object: &T) -> i8 {
        if &self > &object { 1 }
        else if &self == &object { 0 }
        else { -1 }
    }
}

新手对trait理解不深刻,请问该如何一次为多种type实现比较属性?这代码该如何改?

评论区

写评论
7sDream 2020-05-14 19:53

如果只是你这个 case,可以用 where T: PartialOrd

impl<T: PartialOrd> Comparable for T {
    fn compare(&self, object: &T) -> i8 {
        if &self > &object { 1 }
        else if &self == &object { 0 }
        else { -1 }
    }
}

如果是更普遍的情况,可以用宏:

trait Comparable {
    fn compare(&self, object: &Self) -> i8;
}

macro_rules! impl_Compable_for {
    ($($t: ty),+) => {$(
        impl Comparable for $t
        {
            fn compare(&self, object: &$t) -> i8 {
                if &self > &object { 1 }
                else if &self == &object { 0 }
                else { -1 }
            }
        }
    )+}
}

impl_Compable_for!(f64, i32);
1 共 1 条评论, 1 页