I'm trying to make a vector
that would store objects of different structs that implement a certain trait
, however, I really want my trait to be a supertrait of Eq
(and thus PartialEq
).
The Book provides a way to do that with Vec<Box<dyn Draw>>
, however, the PartialEq
dependency seems to disallow this approach with the trait cannot be made into an object error.
This answer provides a way to do a similar thing for HashMap
s. However, this approach seems too verbose for what I am trying to achieve.
What would be the idiomatic way to have a vector for structs implementing such a trait?
Code to reproduce below and on the playground
pub trait MyTrait: PartialEq { fn my_func() -> bool; }
pub struct Struct1 { age: i32 }
impl PartialEq<Self> for Struct1 {
fn eq(&self, other: &Self) -> bool { self.age == other.age }
}
impl MyTrait for Struct1 {
fn my_func() -> bool { false }
}
pub struct Struct2 { year: i32 }
impl PartialEq<Self> for Struct2 {
fn eq(&self, other: &Self) -> bool { self.year == other.year }
}
impl MyTrait for Struct2 {
fn my_func() -> bool { true }
}
fn main() {
let mut v: Vec<Box<dyn MyTrait>> = Vec::new();
// v.push(Struct1 { age: 1 });
// v.push(Struct2 { year: 2 });
}