我试图扩展特征的功能Iterator.
我的statistics/iter_statistics.rs:
mod iter_statistics {
pub trait IterStatistics: Iterator<Item = f64> {
fn foo(&mut self) -> f64 {
0.0
}
}
impl IterStatistics for Iterator<Item = f64> {}
}
Run Code Online (Sandbox Code Playgroud)
而且statistics/mod.rs:
pub use self::iter_statistics::*;
mod iter_statistics;
Run Code Online (Sandbox Code Playgroud)
最后在我的测试代码中
use statistics::IterStatistics;
fn main() {
let z: Vec<f64> = vec![0.0, 3.0, -2.0];
assert_eq!(z.into_iter().foo(), 0.0);
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我得到:
error: no method name `foo` found for type `std::vec::IntoIter<f64>` in the current scope
assert_eq!(z.into_iter().foo(), 0.0);
^~~
Run Code Online (Sandbox Code Playgroud)
这是奇怪,我因为文档的IntoIter<T>说,它实现Iterator<Item=T>.
在impl你写仅适用于特质对象(例如&mut Iterator<Item=f64>),而不是实现所有类型Iterator<Item=f64>.你想写一个impl像这样的泛型:
impl<T: Iterator<Item=f64>> IterStatistics for T {}
Run Code Online (Sandbox Code Playgroud)