如何根据计算值对向量进行排序?

How can I sort a vector by its computed values?

我有以下

use enum_iterator::IntoEnumIterator;

#[derive(Debug, IntoEnumIterator, PartialEq)]
pub enum ResistorColor {
    Black, Blue, Brown, Green,
    Grey, Orange, Red, Violet,
    White, Yellow,
}

pub fn color_to_value(_color: ResistorColor) -> usize {
    //convert a color to a numerical representation
    match _color {
        ResistorColor::Black => 0,
        ResistorColor::Brown => 1,
        ResistorColor::Red => 2,
        ResistorColor::Orange => 3,
        ResistorColor::Yellow => 4,
        ResistorColor::Green => 5,
        ResistorColor::Blue => 6,
        ResistorColor::Violet => 7,
        ResistorColor::Grey => 8,
        ResistorColor::White => 9
    }
}

pub fn value_to_color_string(value: usize) -> String {
    match value {
        0 => "Black".to_string(),
        1 => "Brown".to_string(),
        2 => "Red".to_string(),
        3 => "Orange".to_string(),
        4 => "Yellow".to_string(),
        5 => "Green".to_string(),
        6 => "Blue".to_string(),
        7 => "Violet".to_string(),
        8 => "Grey".to_string(),
        9 => "White".to_string(),
        _ => "Invalid".to_string()
    }
}

pub fn colors() -> Vec<ResistorColor> {
    //reorder the colors to be in order of the value
    let mut colors: Vec<ResistorColor> = ResistorColor::into_enum_iter().collect();
    colors.sort_by(|a, b| color_to_value(a).cmp(&color_to_value(b)));
    colors
}

目前这给我一个类型不匹配的错误,说:

"expected enum 'ResistorColor', found '&ResistorColor'."

我想我理解这条消息,因为参数将只是颜色,即“黑色,棕色”而不是“ResistorColor::Black,ResistorColor::Brown”

如何解决这个问题并对矢量进行排序?

要么将您的函数更改为通过引用接受,则无需获取所有权:

pub fn color_to_value(color: &ResistorColor) -> usize {
                          // ^
    ...
}

或者,像这样的简单枚举很常见,您可以实现 Copy,这样您就可以取消引用 ab 来获取值:

#[derive(Debug, Copy, Clone, IntoEnumIterator, PartialEq)]
             // ^^^^^^^^^^^
pub enum ResistorColor {
    ...
}

colors.sort_by(|a, b| color_to_value(*a).cmp(&color_to_value(*b)));
                                  // ^                       ^

实现排序功能的较短方法是:

colors.sort_by_key(|a| color_to_value(*a))