简体   繁体   English

如何为任何可迭代类型实现特征?

[英]How to implement a trait for any iterable type?

I'd like to implement a generic method that's callable on any container or iterator that iterates over a specific type, eg &[u32] , Vec<u32> , (0..99u32) , etc. 我想实现一个通用方法,该方法可在对特定类型(例如&[u32]Vec<u32> (0..99u32) Vec<u32>(0..99u32)(0..99u32)迭代的任何容器或迭代器上调用。

The following code does not compile: 以下代码无法编译:

trait Foo { fn foo(self); }

impl Foo for std::iter::IntoIterator<Item=u32> {
    fn foo(self) {}
}

error: the value of the associated type IntoIter (from the trait core::iter::IntoIterator ) must be specified [E0191] 错误:必须指定关联类型IntoIter的值(来自特征core::iter::IntoIterator )[E0191]

 impl Foo for std::iter::IntoIterator<Item=u32> { 

What needs to be specified for the IntoIter associated type? 需要为IntoIter关联类型指定什么? ( std::iter::IntoIterator<Item=u32,IntoIter=???> ) std::iter::IntoIterator<Item=u32,IntoIter=???>

so that this would work: 这样就可以了:

vec![0u32].foo()

The correct syntax here is impl<T> SomeTrait for T where T: OtherTrait . 此处的正确语法是impl<T> SomeTrait for T where T: OtherTrait This works: 这有效:

trait Foo { fn foo(self); }

impl<T> Foo for T 
    where T: std::iter::IntoIterator<Item=u32> 
{
    fn foo(self) {}
}

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

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

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