rust - 如何以小写形式显示枚举?

我有一个枚举:

pub enum BoxColour {
    Red,
    Blue,
}

我不仅要get this value as a string , 但我希望将值转换为小写。

这个有效:

impl Display for BoxColour {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(match self {
            BoxColour::Red => "red",
            BoxColour::Blue => "blue",
        })?;
        Ok(())
    }
}

当颜色列表增加时,需要更新此列表。

如果我使用 write! 宏,似乎无法操作结果,因为 write! 返回 () 的实例而不是 String:

impl Display for BoxColour {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:?}", self)
    }
}

这表明这是通过副作用起作用的,也许我们可以破解内存中值所在的相同位置,但即使这是可能的,也可能不是一个好主意......

最佳答案

strum crate 提供了一个派生宏,用于为枚举实现 Display,并可选择小写变体名称:

use strum_macros::Display;

#[derive(Display)]
// If we don't care about inner capitals, we don't need to set `serialize_all` 
// and can leave parenthesis empty.
#[strum(serialize_all = "snake_case")]
pub enum BoxColour {
    Red,
    Blue,
    LightGreen,  // example of how inner capitals are treated
}

fn main() {
    for c in [BoxColour::Red, BoxColor::Blue, BoxColor::LightGreen] {
        println!("{}", c);
    }
}

您还需要在 Cargo.toml 中对 strum 进行相应的依赖:

[dependencies]
strum = { version = "0.21", features = ["derive"] }

这应该打印:

red
blue
light_green

strum 将生成类似于 match with BoxColour::Red => "red", 你提到的情况的代码,但没有需要手动更新它。

https://stackoverflow.com/questions/69015213/

相关文章:

android - 无法查询属性 'namespace' 的值

flutter - 如何在 Flutter 的 FutureBuilder 中调用 setState

regex - 如何在 perl regex 替换命令中使用 unicode 字符?

c++ - 从 std `vector` 库创建的 `` 和从 : `STL vec

python - 正则表达式:在前瞻断言的最后一场比赛之后直到前瞻断言的第一场比赛之后查找文本

python - 无法让 VS Code 将参数从 launch.json 传递给 Python

python - 检查文件夹,如果不存在则创建它

javascript - Vue 3 defineEmits 打破了 defineProps 类型

ios - 是否有修改器可以更改 SwiftUI Picker 的标签颜色?

c++ - 未初始化的引用是否为零初始化和未初始化的标量默认初始化?