I got around the compiler errors:
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;
use serde::ser::{Serialize, Serializer, SerializeStruct};
#[derive(Serialize)]
struct Card {
sections: Vec<Section>
}
#[derive(Serialize)]
struct Section {
header: String,
widgets: Vec<Box<dyn WidgetTrait>>
}
#[derive(Serialize)]
struct Image {
#[serde(rename = "imageUrl")]
image_url: String
}
#[derive(Serialize)]
struct KeyValue {
#[serde(rename = "topLabel")]
top_label: String,
content: String
}
trait WidgetTrait {}
impl Serialize for WidgetTrait {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
let s = serializer.serialize_struct("???", 3)?;
s.end()
}
}
impl WidgetTrait for Image {}
impl WidgetTrait for KeyValue {}
fn main() {
// let test = ResponseMessage {
// text: None,
// cards: Some(
// vec![Card { sections: vec![
// Section { header: format!("text"), widgets: vec![
// Box::new(Image { image_url: format!("img") })
// ]},
// Section { header: format!("text"), widgets: vec![
// Box::new(KeyValue { top_label: format!("text"), content: format!("text") }),
// Box::new(KeyValue { top_label: format!("text"), content: format!("text") })
// ]}
// ]}])
// }
}
Playground
Steps for a working solution.
- Write
as_any()
implementations for your structs that implement WidgetTrait
as per How to get a reference to a concrete type from a trait object?.
- Add implementation for trait
Serialize
of type Box<dyn WidgetTrait>
- Downcast
Box<Widget>
to the struct so we know the type using as_any()
and downcast_ref()
- Use documentation on how to serialize a strongly typed struct
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;
use serde::ser::{Serialize, Serializer, SerializeStruct};
use std::any::Any;
#[derive(Serialize)]
struct Card {
sections: Vec<Section>
}
#[derive(Serialize)]
struct Section {
header: String,
widgets: Vec<Box<dyn WidgetTrait>>
}
#[derive(Serialize)]
struct Image {
#[serde(rename = "imageUrl")]
image_url: String
}
#[derive(Serialize)]
struct KeyValue {
#[serde(rename = "topLabel")]
top_label: String,
content: String
}
trait WidgetTrait {
fn as_any(&self) -> &Any;
}
impl Serialize for Box<dyn WidgetTrait> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
return match self.as_any().downcast_ref::<Image>() {
Some(img) => {
let mut widget_serializer = serializer.serialize_struct("Image", 1)?;
widget_serializer.serialize_field("imageUrl", &img.image_url)?;
widget_serializer.end()
},
None => {
let key_value: &KeyValue = match self.as_any().downcast_ref::<KeyValue>() {
Some(k) => k,
None => panic!("Unknown type!")
};
let mut widget_serializer = serializer.serialize_struct("KeyValue", 2)?;
widget_serializer.serialize_field("topLabel", &key_value.top_label)?;
widget_serializer.serialize_field("content", &key_value.content)?;
widget_serializer.end()
}
};
}
}
impl WidgetTrait for Image {
fn as_any(&self) -> &Any {
self
}
}
impl WidgetTrait for KeyValue {
fn as_any(&self) -> &Any {
self
}
}
fn main() {
// let test = ResponseMessage {
// text: None,
// cards: Some(
// vec![Card { sections: vec![
// Section { header: format!("text"), widgets: vec![
// Box::new(Image { image_url: format!("img") })
// ]},
// Section { header: format!("text"), widgets: vec![
// Box::new(KeyValue { top_label: format!("text"), content: format!("text") }),
// Box::new(KeyValue { top_label: format!("text"), content: format!("text") })
// ]}
// ]}])
// }
}
Playground
Section
struct will not allow you to store different Widgets which implementWidgetTrait
, because Rust monomorphises generics during compilation. Just FYI, the boxed trait is generally good way to go, or anRc
, depending on your use case – MaryroseSerialize
manually forSection
. Even if everyWidgetTrait
type implementsSerialize
, that doesn't mean that the typeWidgeTrait
itself does. In fact there's no way to automatically implement that. – TickerSerialize
forBox
? – Nyctaginaceousstruct
comes from theBox<WidgetTrait>
to be able to use the strongly typedserializer
– Evvy