I am trying to achieve the following code:
#[derive(Debug, Serialize, Deserialize)]
struct SomeFoo {
name: String,
age: i32,
}
fn test(req: SomeFoo) -> i32 {
println!("Value: {:?}", req);
5
}
fn main() {
let mut handlers = HandlerMap::new();
handlers.add("foobar1", &test);
let payload = r#"
{
"name": "John Doe",
"age": 43
}"#;
let result = handlers.dispatch("foobar1", payload);
println!("Result: {}", result);
}
I tried a few approaches to allow to register a function that can than be later called with the correct argument. The most promising was to create a trait that specified a method call_with_json()
and then implement it for the type fn(T)
.
trait CallHandler {
fn call_with_json(&self, req: &str) -> i32;
}
impl<T> CallHandler for fn(T) -> i32
where
T: DeserializeOwned,
{
fn call_with_json(&self, req: &str) -> i32 {
let req: T = serde_json::from_str(req).expect("bad json");
(self)(req)
}
}
Here playground link with the full impl. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=566e33aab2e3c6d3a090d3b9831a4358
Rust keeps telling me that the trait CallHandler
is not implemented for fn item fn(SomeFoo) -> i32 {test}
Not sure what I am missing here.