简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM