本文介绍了如何在各种类型的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(); } 推荐答案您不能直接执行通用表单,即问题#20400 .您必须引入一个可以用作 T :: Item 的绑定的特征,或者合并包装器类型.例如.第一个可能看起来像:
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项上允许特征的多种实现?
发布评论