所以我有
#[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}");
}
您甚至可以基于此实现枚举的显示:
impl fmt::Display for ComparisonOperators {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
请记住,
Display
免费为您提供 ToString
实现。
如果你只是想用它来实现 Display,则不需要依赖 serde_json,因为 serde 实现了 Serializer for std::fmt::Formatter 这是实现 Display 时得到的。
impl Display for ComparisonOperators{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.serialize(f)
}
}