如何从枚举值中获取重命名的枚举名称?

How to get renamed enum name from enum value?

所以我有

#[derive(Deserialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

我想从 let i = ComparisonOperators::GE">="。我可以通过不添加映射器来做到这一点吗?

您可以添加 Serialize 标签,然后使用 serde_json 序列化为 String 根据您的属性重命名:

use serde::{Deserialize, Serialize};
use serde_json; // 1.0.78

#[derive(Deserialize, Serialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

fn main() {
    let tag = serde_json::to_string(&ComparisonOperators::EQ).unwrap();
    println!("{tag}");
}

Playground

您甚至可以基于此为您的枚举实现显示:

impl fmt::Display for ComparisonOperators {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(self).unwrap())
    }
}

Playground

请记住,Display 免费为您提供 ToString 实施。