Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 24, 2020 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/7c1531584e37a9853c685ce47cefffc6 to your computer and use it in GitHub Desktop.
Save rust-play/7c1531584e37a9853c685ce47cefffc6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![feature(extern_prelude)]
extern crate serde; // 1.0.68
#[macro_use]
extern crate serde_derive; // 1.0.68
use std::collections::HashMap;
use serde::*;
use std::fmt::{Display, Formatter};
use serde::ser::{Serialize, Serializer, SerializeSeq, SerializeMap};
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
struct Foo{x: u64}
#[derive(Deserialize, Debug)]
struct Bar {
x: HashMap<Foo, f64>,
}
impl Display for Foo {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "{}", self.x)
}
}
impl Serialize for Bar {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_map(Some(self.x.len()))?;
for (k, v) in &self.x {
seq.serialize_entry(&k.to_string(), &v)?;
}
seq.end()
}
}
fn main() {
let mut p = Bar{x: HashMap::new()};
p.x.insert(Foo{x:0}, 0.0);
let serialized = serde_json::to_string(&p).unwrap();
println!("{:?}", serialized)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment