-
-
Save rust-play/37e864f6c06fe0a346b24151ed7fa7b4 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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