首页 > 解决方案 > 基于封装数据的 Rust Enums 的 PartialOrd

问题描述

我有一个枚举,它将数字基元(u8、i8、u16、i16、u32、i32、u64、i64、f32、f64)封装成一种称为“数字”的通用类型。我想根据封装的数据为枚举实现 PartialOrd 训练,允许比较不同的数字。我有一个使用嵌套模式匹配和强制转换的解决方案,但它看起来很笨拙。有一个更好的方法吗?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7edcbe456847fb129475ee40568d21c2

use std::cmp::Ordering;

#[derive(PartialEq)]
enum Number {
    U8(u8),
    I8(i8),
    U16(u16),
    I16(i16)
}

impl PartialOrd for Number {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        // self.height.partial_cmp(&other.height)
        match self {
            Number::U8(x) => {
                match other {
                    Number::U8(y) => (*x).partial_cmp(y),
                    Number::I8(y) => (*x as i16).partial_cmp(&(*y as i16)),
                    Number::U16(y) => (*x as u16).partial_cmp(y),
                    Number::I16(y) => (*x as i32).partial_cmp(&(*y as i32)),
                }
            },
            Number::I8(x) => {
                match other {
                    Number::U8(y) => (*x as i16).partial_cmp(&(*y as i16)),
                    Number::I8(y) => (*x).partial_cmp(y),
                    Number::U16(y) => (*x as u16).partial_cmp(y),
                    Number::I16(y) => (*x as i32).partial_cmp(&(*y as i32)),
                }
            },
            Number::U16(x) => {
                match other {
                    Number::U8(y) => (*x).partial_cmp(&(*y as u16)),
                    Number::I8(y) => (*x as i32).partial_cmp(&(*y as i32)),
                    Number::U16(y) => (*x).partial_cmp(y),
                    Number::I16(y) => (*x as i32).partial_cmp(&(*y as i32)),
                }
            },
            Number::I16(x) => {
                match other {
                    Number::U8(y) => (*x).partial_cmp(&(*y as i16)),
                    Number::I8(y) => (*x).partial_cmp(&(*y as i16)),
                    Number::U16(y) => (*x as i32).partial_cmp(&(*y as i32)),
                    Number::I16(y) => (*x).partial_cmp(y),
                }
            },
        }
    }
}

标签: rustcastingpattern-matchingpartial-ordering

解决方案


推荐阅读