Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 17, 2023 09:46
Show Gist options
  • Save rust-play/d4ae6ae4c1eb705a8ba8dfdfedd3b766 to your computer and use it in GitHub Desktop.
Save rust-play/d4ae6ae4c1eb705a8ba8dfdfedd3b766 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use serde; // 1.0.152
use serde_json; // 1.0.91
/// Foo struct
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct FooV1 {
msg: String,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct FooV2 {
msg: String,
#[serde(default = "FooV2::default_version")]
version: u64,
}
impl FooV2 {
pub fn default_version() -> u64 {
4
}
}
fn main() {
// Assert that v2 encoded message can be read by v1 serde deserializer.
let foo_v2 = FooV2 {
msg: "message".to_string(),
version: 5,
};
let serialized_foo_v2 = serde_json::to_string(&foo_v2).unwrap();
println!("FooV2 debug: {:?}", foo_v2);
println!("Serialized FooV2: {}", serialized_foo_v2);
let foo_v1: FooV1 = serde_json::from_str(&serialized_foo_v2).unwrap();
println!("FooV1 debug: {:?}", foo_v1);
// Assert that serde::default makes v1 message readble by v2 deserializer
let serialized_foo_v1 = serde_json::to_string(&foo_v1).unwrap();
println!("Serialized FooV1: {}", serialized_foo_v1);
let foo_v2_from_v1: FooV2 = serde_json::from_str(&serialized_foo_v1).unwrap();
println!("FooV2 from v1 debug: {:?}", &foo_v2_from_v1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment