【问题标题】:Matching on enum : First arm unexpectedly always matching枚举匹配:第一臂意外总是匹配
【发布时间】:2021-04-16 13:46:38
【问题描述】:

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

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) -> ""

【问题讨论】:

  • 这是一个常见错误,但编译器警告非常有效地捕获了该错误。如果您将它们关闭,请考虑将它们打开,并实际检查它们 - 这将使您使用 Rust 的体验更加愉快。
  • 我同意。我非常专注于添加下一个功能,并将警告留到以后。我经常这样做是因为当我开始实现时有很多未使用的变量和函数。这是一个错误。

标签: rust enums pattern-matching


【解决方案1】:

这是因为所有可能的值都与 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::*;,但您很容易受到拼写错误或更改的影响。

【讨论】:

  • 编译器会生成警告页面,指出它:无法访问的模式警告,pattern with name of variant,未使用的值,局部变量名格式警告,...这 11 行生成 19 种不同的警告,你我认为这会很明显。
  • 你说的都是对的。为我解决这个问题真是太棒了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
相关资源
最近更新 更多