No method found when extending the Iterator trait in Rust
我正在尝试扩展
我的
1 2 3 4 5 6 7 8 9 | mod iter_statistics { pub trait IterStatistics: Iterator<Item = f64> { fn foo(&mut self) -> f64 { 0.0 } } impl IterStatistics for Iterator<Item = f64> {} } |
和
1 2 | pub use self::iter_statistics::*; mod iter_statistics; |
最后在我的测试代码中,我有
1 2 3 4 5 6 | use statistics::IterStatistics; fn main() { let z: Vec<f64> = vec![0.0, 3.0, -2.0]; assert_eq!(z.into_iter().foo(), 0.0); } |
运行测试时,我得到:
1 2 3 | error: no method name `foo` found for type `std::vec::IntoIter<f64>` in the current scope assert_eq!(z.into_iter().foo(), 0.0); ^~~ |
这对我来说很奇怪,因为
您编写的
1 | impl<T: Iterator<Item=f64>> IterStatistics for T {} |
您的实现落后。在Rust中进行编程时,您必须忘记OO继承和功能方面的原因。
What does
trait D: B means in Rust?
这意味着
When to use
trait D: B then?
使用此约束的主要原因是,当您希望提供
通常,您不想添加超出严格限制的限制,因为您的客户可能希望以您未预见的方式使用此特征。
一个例外是在将特征创建为"约束束"时,因此对于要实现的所有方法,您不必都键入
So, how to extend
Iterator ?
首先声明一个新特征:
1 2 3 | pub trait IterStatistics { fn foo(&mut self) -> f64; } |
然后对已经实现
的所有类型实现它
1 2 3 4 5 6 7 | impl< T > IterStatistics for T where T: Iterator<Item = f64> { fn foo(&mut self) -> f64 { 0.0 } } |