I know I should use composition instead of inheritance.
In Java/C++, I have an abstract base class Vehicle
(with properties and common methods) and classes which implement this, such as Car
and Bike
.
I've found enum_dispatch
, which does a great job of forwarding method calls from the parent to the child "classes".
#[enum_dispatch]
pub trait VehicleDelegation {
fn drive(&mut self) -> anyhow::Result<()>;
}
#[enum_dispatch(VehicleDelegation)]
pub enum Vehicle {
Car,
Bike,
}
pub struct Car {
pub doors: u8
}
impl VehicleDelegation for Car {
fn drive(&mut self) -> anyhow::Result<()> {
// do car stuff
Ok(())
}
}
pub struct Bike {
pub frame_size: u8
}
impl VehicleDelegation for Bike {
fn drive(&mut self) -> anyhow::Result<()> {
// do bike stuff
Ok(())
}
}
- Where should I store common data, such as
num_wheels
which would have been properties ofVehicle
? - Where should I define methods of
Vehicle
which use the common data?
At the moment I have to duplicate all of the Vehicle
data and methods into every enum variant, which is getting tiresome as it scales with both the number of "methods" and the number of "classes".
- How do I do this idiomatically in Rust?