Skip to content

Instantly share code, notes, and snippets.

@boxofrox
Forked from anonymous/playground.rs
Created May 30, 2017 03:20
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 boxofrox/ea36ad33de01ebebd9024b9ec54fe925 to your computer and use it in GitHub Desktop.
Save boxofrox/ea36ad33de01ebebd9024b9ec54fe925 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::collections::HashMap;
use serde::{Serialize, Serializer};
fn main() {
let mut map: HashMap<String, String> = HashMap::new();
map.insert("hello".into(), "world".into());
let data = ApiResult::Success(map.keys());
println!("{}", serde_json::to_string(&data).unwrap());
}
#[derive(Serialize)]
#[serde(bound(serialize = "T: Clone + Iterator, T::Item: Serialize"))]
pub enum ApiResult<'a, T> {
Failure { code: u32, errors: Vec<&'a str> },
Success(#[serde(serialize_with = "serialize_iter")] T),
}
fn serialize_iter<T, S>(iter: &T, serializer: S) -> Result<S::Ok, S::Error>
where T: Clone + Iterator,
T::Item: Serialize,
S: Serializer
{
serializer.collect_seq(iter.clone())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment