如何允许在各种类型的 IntoIterator 项目上多次实现特征?
How to allow multiple implementations of a trait on various types of IntoIterator items?
Rust 似乎不会区分特征的不同实现,仅当它们在关联类型上有所不同时。
如何在各种 collections/iterators 上实现一个方法,但对它们包含的每个具体类型都有特定的实现?
error: conflicting implementations for trait 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();
}
不能直接做泛型,也就是issue #20400。您必须引入可用作 T::Item
上的绑定以合并两个实现或包装器类型的特征。例如。第一个可能看起来像:
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
{
...
}
Rust 似乎不会区分特征的不同实现,仅当它们在关联类型上有所不同时。
如何在各种 collections/iterators 上实现一个方法,但对它们包含的每个具体类型都有特定的实现?
error: conflicting implementations for trait
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();
}
不能直接做泛型,也就是issue #20400。您必须引入可用作 T::Item
上的绑定以合并两个实现或包装器类型的特征。例如。第一个可能看起来像:
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
{
...
}