I have difficulty understanding how to deal with polymorphic objects. I have JSON input which I want to deserialize as a struct which can hold another struct of type A
or B
. Each one implements the G
trait:
pub trait Action {}
impl Action for SendMessage {}
#[derive(Debug, Deserialize, Serialize)]
struct SendMessage {
msg: String,
}
impl Action for SendEmail {}
struct SendEmail {
recipient: String,
msg: String,
}
#[derive(Debug, Deserialize, Serialize)]
struct ApiResponse<T: Action> {
status: String,
data: T,
}
fn main() {
let payload = r#"
{
"status": "200",
"data": {
"msg": "toto"
}
}
"#;
let test: ApiResponse = serde_json::from_str(payload).unwrap(); // Return Error
let test: ApiResponse<SendEmail> = serde_json::from_str(payload).unwrap(); // Is ok
let test: ApiResponse<SendMessage> = serde_json::from_str(payload).unwrap(); // Return Error
}
What is the idiomatic way to store the result in my test
variable if I don't know the content of my payload?