枚举匹配:第一个手臂意外地总是匹配

问题描述

我手头有一个最奇怪的案例。我有一个可以转换为字符串的枚举。提供的枚举是例如。绿色所以从匹配返回的字符串是“text-success”。简单吧?事实证明,无论我如何获得它,返回的字符串始终是“”。这对我来说毫无意义。请帮忙!

fn bootstrap_table_color (e: Color) -> String {
    let s: String = match &e {
        White => "".to_string(),Blue => String::from("table-info"),Green => "table-success".to_string(),Yellow => "table-warning".to_string(),Red => "table-danger".to_string(),};
    println!("bootstrap_table_color ({:?}) -> {:?}",e,s);
    return s;
}

bootstrap_table_color (Blue) -> ""
bootstrap_table_color (Green) -> ""

解决方法

那是因为所有可能的值都匹配 White 变量臂。

你可以看到它

let s: String = match &e {
    White => format!("White={:?}",White),}

干净的解决方案是在 arm 值前面加上你的枚举名称:

let s = match &e {
    Color::White => "".to_string(),Color::Blue => String::from("table-info"),Color::Green => "table-success".to_string(),Color::Yellow => "table-warning".to_string(),Color::Red => "table-danger".to_string(),};

另一种解决方案是执行 use Color::*;,但您很容易出现拼写错误或更改。