I am using Serde to deserialize BSON objects to Rust struct instances. I can deserialize the objects to concrete struct instances, but how can I deserialize generically?
I have "countries" and "cities" collections in MongoDB. In the Rust program, I have a struct for Country and City. When I pull a country or a city from Mongo, I can deserialize it using Serde to the Country or City struct. See the second line in main() below.
I want to deserialize the BSON object into a generic Location object. Based on what I read about generics in the Rust book, I created a trait LocationTrait and implemented it for Country and City. (see line 3 in main()). It fails to compile, saying
the size for values of type dyn LocationTrait cannot be known at compilation time.
#[derive(Serialize, Deserialize)]
pub struct Country {
pub name: String,
}
#[derive(Serialize, Deserialize)]
pub struct City {
pub name: String,
}
pub trait LocationTrait {}
impl LocationTrait for Country {}
impl LocationTrait for City {}
fn main() {
let item = mongo_coll
.find_one(Some(doc! {"name": "usa"}), None)
.unwrap()
.unwrap();
let country: Country = bson::from_bson(bson::Bson::Document(item)).unwrap();
// fails -> let gen_location: LocationTrait = bson::from_bson(bson::Bson::Document(item)).unwrap();
}
Eventually, I would like to create a generic object that represents Country or a City. But, I am not sure of the starting point -- do I need to focus on a trait or do I need to create a new trait-bound struct?