简体   繁体   English

Rust:特征内的类型引用

[英]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?是否可以引入一个新的计算类型变量,这样我就可以避免在任何地方输入<Self as IntoIterator>::Item A simple type Item = <Self as IntoIterator>::Item does not work because that is an associated type that could potentially be overridden.一个简单的type Item = <Self as IntoIterator>::Item不起作用,因为这是一个可能被覆盖的关联类型。 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.使用类型参数作为MyVec<I>也不起作用,因为我不想用不同的I类型为同一个结构实现这个特性,并且在以后编写通用代码时也会导致问题。 Any recommendations?有什么建议吗?

I don't think you can define a type in the trait as implementors then could customize this type.我不认为你可以在trait中定义一个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 :或者,作为 hack,您可以尝试MyVec<I> ,但使用默认值I

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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