如何在各种类型的IntoIterator项上允许特征的多种实现? [英] How to allow multiple implementations of a trait on various types of IntoIterator items?

查看:59
本文介绍了如何在各种类型的IntoIterator项上允许特征的多种实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有在特征的不同实现之间因关联类型不同而不同时,Rust似乎无法区分它们.

Rust doesn't seem to distinguish between different implementations of a trait only if they differ by an associated type.

如何在所有类型的集合/迭代器上实现一种方法,但是对于它们所包含的每种具体类型都有特定的实现?

How can I implement a method on all kinds of collections/iterators, but have specific implementations for each concrete type they contain?

错误:特征 Foo [E0119]

代码:

trait Foo { fn foo(self); }

impl<T> Foo for T 
    where T: IntoIterator<Item=u32> 
{
    fn foo(self) {
        self.into_iter();
    }
}

impl<T> Foo for T 
    where T: IntoIterator<Item=u16> 
{
    fn foo(self) {
        self.into_iter();
    }
}

fn main() {
    vec![0u32].foo();
    vec![0u16].foo();
}

推荐答案

您不能直接执行通用表单,即

You can not do the generic form directly, which is issue #20400. You'll have to introduce either a trait that can be used as a bound on T::Item to merge the two implementations, or wrapper types. E.g. the first one might look like:

trait FooIterItem {
    // behaviours needed for Foo impl
}
impl FooIterItem for u32 { ... }
impl FooIterItem for u16 { ... }

impl<T> Foo for T
    where T: IntoIterator, T::Item: FooIterItem
{
    ...
}

这篇关于如何在各种类型的IntoIterator项上允许特征的多种实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆