I have a basic struct called Frame
that is useful for a bunch of calculations:.
pub struct Frame {
grid_val: Vec,
gri
It appears you want an associated type:
pub trait Algorithm<T> {
type Output;
fn calculate_something(&self) -> Result<Self::Output, Error>;
}
impl<T> Algorithm<T> for Sphere<T> {
type Output = Sphere<T>;
fn calculate_something(&self) -> Result<Self::Output, Error> {
unimplemented!()
}
}
impl<T> Algorithm<T> for Hyperbola<T> {
type Output = Hyperbola<T>;
fn calculate_something(&self) -> Result<Self::Output, Error> {
unimplemented!()
}
}
Associated types are described in detail in The Rust Programming Language. I highly recommend reading through the entire book to become acquainted with what types of features Rust has to offer.
An alternate solution is to define another generic type on the trait:
pub trait Algorithm<T, Out = Self> {
fn calculate_something(&self) -> Result<Out, Error>;
}
impl<T> Algorithm<T> for Sphere<T> {
fn calculate_something(&self) -> Result<Sphere<T>, Error> {
unimplemented!()
}
}
impl<T> Algorithm<T> for Hyperbola<T> {
fn calculate_something(&self) -> Result<Hyperbola<T>, Error> {
unimplemented!()
}
}
You then need to decide When is it appropriate to use an associated type versus a generic type?