Search code examples
rusttraitstype-parameter

Rust: type reference within trait


I would like to implement my own generic container, and this is the fragment of a trait I am using:

pub trait MyVec
where
    Self: Default + Clone + IntoIterator,
    Self: std::iter::FromIterator<<Self as IntoIterator>::Item>,
{
    fn get(self: &Self, index: usize) -> <Self as IntoIterator>::Item;

    // many other methods are omitted.
}

Is it possible to introduce a new computed type variable so that I can avoid typing <Self as IntoIterator>::Item everywhere? A simple type Item = <Self as IntoIterator>::Item does not work because that is an associated type that could potentially be overridden. Using a type parameter as MyVec<I> does not work either as I do not want to implement this trait with different I types for the same struct, and it also causes problem when writing generic code later. Any recommendations?


Solution

  • I don't think you can define a type in the trait as implementors then could customize this type.

    But you could introduce a type alias outside the trait:

    pub type IntoIterItem<T> = <T as IntoIterator>::Item;
    
    pub trait MyVec : 
        Default
        + Clone
        + IntoIterator
        + std::iter::FromIterator<IntoIterItem<Self>>
    {
        fn get(self: &Self, index: usize) -> IntoIterItem<Self>;
    }
    

    Or, as a hack, you could try MyVec<I>, but with a default I:

    pub trait MyVec<Item=<Self as IntoIterator>::Item> : 
        Default
        + Clone
        + IntoIterator
        + std::iter::FromIterator<Item>
    {
        fn get(self: &Self, index: usize) -> Item;
    }