Hi, I'm learning rust and I would like to get some help regarding the code design.
I'm writing a simple "controller" and I would like to split the IO and core logic operations so that I could reuse the core logic for different input formats. What is a preferred way of doing it?
This is a bit vague and so bellow is a simple example. The question is whether ControllerInput
should be a struct
or a trait
in order to integrate it with custom ServiceInput
.
First option: input as a struct
+ From
trait
struct ControllerInput {
x: f32,
}
struct Controller {}
impl Controller {
fn compute(&self, input: ControllerInput) {
todo!();
}
}
struct ServiceInput {
y: f32,
}
impl From<ServiceInput> for ControllerInput {
fn from(value: ServiceInput) -> Self {
Self { x: value.y }
}
}
Second option: input as a trait
trait ControllerInput {
fn x(&self) -> f32;
}
struct Controller<T> {
data: std::marker::PhantomData<T>,
}
impl<T: ControllerInput> Controller<T> {
fn compute(&self, input: T) {
todo!()
}
}
struct ServiceInput {
y: f32,
}
impl ControllerInput for ServiceInput {
fn x(&self) -> f32 {
self.y
}
}
Which option is more idiomatic? What are the advanteges and disadvantages of both options? Are there any other alternatives?