Hi, I'm new in Rust and I'm doing a code test to be familiar with the language.
In the code test I have a method which return a heterogenous collection of "BoardingPass" (it could be a bus, train or any other type). Here is the code:
pub fn generate<'a>(&'a self) -> Vec<Box<BoardingPass + 'a>> {
let mut vector: Vec<Box<BoardingPass>> = Vec::new();
let madrid_barna = BoardingPassTrain::new("1", &self.madrid, &self.barna);
vector.push(Box::new(madrid_barna));
let barna_madrid = BoardingPassTrain::new("2", &self.barna, &self.madrid);
vector.push(Box::new(barna_madrid));
vector
}
https://github.com/fjbelchi/CodeTest-BoardingPass-Rust
The BoardingPass trait I would like to inherit from Hash + PartialEq in order to let me sort the collection easily.
pub trait BoardingPass : Hash + PartialEq + Debug {
fn boarding_id(&self) -> &str;
fn city_from(&self) -> &City;
fn city_to(&self) -> &City;
}
That produce the following compilation error:
src/sort/boarding_pass_generator.rs:18:46: 18:63 error: the trait `models::boarding_pass::BoardingPass` cannot be made into an object [E0038]
src/sort/boarding_pass_generator.rs:18 pub fn generate<'a>(&'a self) -> Vec<Box<BoardingPass + 'a>> {
^~~~~~~~~~~~~~~~~
src/sort/boarding_pass_generator.rs:18:46: 18:63 help: run `rustc --explain E0038` to see a detailed explanation
src/sort/boarding_pass_generator.rs:18:46: 18:63 note: the trait cannot use `Self` as a type parameter in the super trait listing
I'm not 100% sure about what the error means, but I guess it could be related to the heterogenous collection with PartialEq Trait due to we can't probably check equality for BoardingPassBus = BoardingPassTrain because the types are different.
I would like to add a default implementation of PartialEq for the BoardingPass Trait, something like:
impl PartialEq for BoardingPass {
fn eq(&self, other: &BoardingPass) -> bool {
self.boarding_id() == other.boarding_id()
}
}
I did this same exercise in Swift and I had to create a wrapper AnyBoardingPass to work around this issue. Which options can I have in Rust? - Probably I could do the same, but I would like to explore other alternatives that probably I'm not aware of.
Thank you