I have different structs which I am storing in a HashMap
. These structs are sharing similar methods, but have also their own specific methods. I want to store all the different structs in a HashMap
, and be able to access both the trait methods and the specific methods belonging to each struct.
As of now, I've found a great way of using the trait methods of structs stored in a HashMap
, but my problem is now to access the methods belonging to each specific struct.
This is a very simplified structure of my code:
struct A {value_only_A_has: f64, common_value: u32}
impl A {
fn method_a() {
// Does something very specific and only related to A...
}
}
impl Common for A {
fn method_common(&mut self) -> () {
// Does something which is related to all structs, but properties are only
// related to A (the reason for using traits).
}
}
struct B {value_only_B_has: f64, common_value: u32}
impl B {
fn method_b() {
// Does something very specific and only related to B...
}
}
impl Common for B {
fn method_common(&mut self) -> () {
// Does something which is related to all structs, but properties are only
// related to B (the reason for using traits).
}
}
trait Common {
// Does something which is related to all structs.
fn method_common(&mut self) -> ();
}
This is a very simplified explanation of what I want to do:
// Store all different kind of structures in a HashMap container.
let mut container: HashMap<u32, Box<dyn Common>> = HashMap::new();
let a = A {value_only_A_has: 10.0, common_value: 3};
let b = B {value_only_B_has: 20.0, common_value: 2};
container.insert(0, Box::new(a));
container.insert(1, Box::new(b));
// This trait method is easy to access (this works):
container.get(&1).unwrap().method_common();
// I want to somehow get access to the method
// belonging to each struct (this does not work):
match container.get(&1).unwrap() {
A(v) => v.method_a(),
B(v) => v.method_b(),
}
How can I access the methods specific to each struct by using something ideally similar to this?
(Edit: After playing around with Box
, it seems that the only thing stored in container
are the trait methods, and not the actual struct with the specific methods. Maybe my approach by storing the structs in container
as trait and Box in the way I've done it is wrong?)