Serdeのenumの挙動
JSON-RPCにある、次のような構造を生成するためのソースコード。untaggedとかinternally taggedを組み合わせたときの挙動を想像するのは時として難しいので、さくっと実験したほうが速い。Serdeのドキュメント は役に立つ。
{"method":"write","params":{"content":4919}}
Container { method: Read }
extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Container {
#[serde(flatten)]
method: Method,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "method", content = "params")]
pub enum Method {
#[serde(rename = "write")]
Write {
content: usize,
},
#[serde(rename = "read")]
Read,
}
fn main() {
let call = Container { method: Method::Write { content: 0x1337 } };
let serialized = serde_json::to_string(&call).unwrap();
println!("{serialized}");
let input = r#"{"method": "read"}"#;
let deserialized: Container = serde_json::from_str(&input).unwrap();
println!("{deserialized:?}");
}
Backlinks
There are no notes linking to this note.