How can we return an anonymous type in Result trait

Hi ,
I try to re implement a java script microservice project (https://moleculer.services/) to rust .
when i try to call an rpc and return value , the remote function result may be anonymous , i write a sample code that i want to run but i got error .
you can see my problem in https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bc00eaab1d0d3f0f2b69346f80fa0953 , please help me how can i pass my values to json api that returns various type .

You can't use the trait Any here. Instead you need some trait that allows the type to be created from a json string. For this you can use serde:

where
    R: serde::de::DeserializeOwned,

Then when you call it you can specify the value of R in each situation. For more specifics, I'd need to know what web crate you're using.

3 Likes

Hi alice ,
Thanks and i try it now .
may i have a sample code in plyground ?

I think this is the kind of pattern you can use:


extern crate serde;
extern crate serde_json;

use serde::{
    Deserialize,
    de::DeserializeOwned,
};

pub fn foo<R: DeserializeOwned>() -> Result<R, serde_json::Error> {
    let stuff = r#" { "a": "foo", "b": 32 } "#;
    serde_json::from_str(stuff)
}

fn main() {
    #[derive(Deserialize, Debug)]
    struct Bar {
        a: String,
        b: i32,
    }
    let a: Bar = foo().unwrap();
    dbg!(a);
    
    let b: serde_json::Value = foo().unwrap();
    dbg!(b);
}
1 Like