I am new to Rust. My background is Java. I am trying to solve the following problem.
- I have a
trait Fuel
which is implemented forstruct Diesel
andstruct Gas
. - I also have a
trait Vehicle
withFuel
generic type parameter. Vehicle is implemented forstruct Car<F: Fuel>
andstruct Bus<F: Fuel>
.
Finally I want to put references to possible heterogeneous trait objects to one Vec
like this:
let diesel_car = Car { fuel: Diesel {} };
let gas_car = Car { fuel: Gas {} };
let diesel_bus = Bus { fuel: Diesel {} };
let gas_bus = Bus { fuel: Gas {} };
let garage = vec![
&diesel_car,
&gas_car,
&diesel_bus,
&gas_bus
];
But I get this compile error:
error[E0308]: mismatched types
--> src/main.rs:63:9
|
63 | &gas_car,
| ^^^^^^^^ expected struct `Diesel`, found struct `Gas`
|
= note: expected type `&Car<Diesel>`
found reference `&Car<Gas>`
What should be the generic type of references in this Vec? It guess it should be something like Vec<&dyn Vehicle>
. But this variant doesn't compile either since it wants to know the generic type parameter of Vehicle
in advance. In Java I would just write List<Vehicle<?>
. Is there anything similar in Rust?
The whole example is available in the playground.
P.S. I can obviously remove a generic parameter from Vehicle
and replace it with Box<dyn Fuel>
, but I would like to minimize places with dynamic dispatch.