Simple organization of Rust traits for “polymorphic” return

前端 未结 1 1293
野的像风
野的像风 2021-01-13 23:30

I have a basic struct called Frame that is useful for a bunch of calculations:.

pub struct Frame {
    grid_val: Vec,
    gri         


        
相关标签:
1条回答
  • 2021-01-13 23:55

    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?

    0 讨论(0)
提交回复
热议问题