Trait serde_traitobject::Serialize
source · pub trait Serialize: Sealed { }
Expand description
Any trait with this as a supertrait can be serialized as a trait object.
It is automatically implemented for all T: serde::Serialize
, i.e. you should not implement it manually.
To use, simply add it as a supertrait to your trait:
use serde_derive::{Serialize, Deserialize};
trait MyTrait: serde_traitobject::Serialize + serde_traitobject::Deserialize {
fn my_method(&self);
}
Now your trait object is serializable!
#[derive(Serialize, Deserialize)]
struct Message(#[serde(with = "serde_traitobject")] Box<dyn MyTrait>);
// Woohoo, `Message` is now serializable!
Any implementers of MyTrait
would now have to themselves implement serde::Serialize
and serde::de::DeserializeOwned
. This would typically be through serde_derive
, like:
#[derive(Serialize, Deserialize)]
struct MyStruct {
foo: String,
}
impl MyTrait for MyStruct {
fn my_method(&self) {
println!("foo: {}", self.foo);
}
}