Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 21, 2022 05:33
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/37e864f6c06fe0a346b24151ed7fa7b4 to your computer and use it in GitHub Desktop.
Save rust-play/37e864f6c06fe0a346b24151ed7fa7b4 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use serde::Deserialize;
use serde_json;
use std::marker::PhantomData;
#[derive(Deserialize, Debug)]
struct Ping<'a> {
#[serde(borrow)]
ping: &'a str,
}
struct Handler<T> {
data: String,
_marker: PhantomData<T>,
}
impl<'de, T: Deserialize<'de>> Handler<T> {
fn new(data: String) -> Self {
Self {
data,
_marker: PhantomData::default(),
}
}
fn handle(&'de self, callback: impl FnOnce(T)) {
let res: T = serde_json::from_str(&self.data).unwrap();
callback(res);
}
}
fn main() {
let callback = |p: Ping| println!("{:?}", p);
Handler::<Ping>::new(format!("{{\"ping\":\"{}\"}}", "abcdefg")).handle(callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment