如何解决结构体中的枚举数组打印变量名称和值
我有一个使用枚举的结构,但是在打印时它给出了枚举名称和值,而不仅仅是值。我想使用 serde_json 序列化它以作为 JSON 请求发送。
我想对 geth json-rpc 的不同命令重复使用结构,而不是为每种类型的命令制作不同的结构。这就是为什么我想到使用枚举。但我做错了什么。可能是打印,但 json-rpc 说参数也无效。
use serde::{Deserialize,Serialize};
#[derive(Debug,Serialize,Deserialize)]
enum Params {
String (String),Boolean (bool)
}
#[derive(Debug,Deserialize)]
struct EthRequest {
jsonrpc : String,method: String,params: [Params; 2],id: i32
}
fn main() {
let new_eth_request = EthRequest {
jsonrpc : "2.0".to_string(),method : "eth_getBlockByNumber".to_string(),params : [Params::String("latest".to_string()),Params::Boolean(true)],id : 1
};
println!("{:#?}",new_eth_request);
}
输出:
EthRequest {
jsonrpc: "2.0",method: "eth_getBlockByNumber",params: [
String(
"latest",),Boolean(
true,],id: 1,}
我需要的是 params 字段为 params: ["latest",true]
解决方法
提供的输出来自 Debug
实现,而不是来自 serde。从 serde 你会得到:
{
"jsonrpc": "2.0","method": "eth_getBlockByNumber","params": [
{
"String": "latest"
},{
"Boolean": true
}
],"id": 1
}
我猜您想删除枚举值前面的标记 String
和 Boolean
。这很容易做到,只需使用 #[serde(untagged)]
注释您的枚举:
#[derive(Debug,Serialize,Deserialize)]
#[serde(untagged)]
enum Params {
String (String),Boolean (bool)
}
你会得到预期的输出:
{
"jsonrpc": "2.0","params": [
"latest",true
],"id": 1
}
中了解有关不同枚举表示的更多信息版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。