在下面的示例中,MyTrait扩展了IntoIterator,但是编译器在循环中使用时不识别它。
pub trait MyTrait: IntoIterator<Item = i32> {
fn foo(&self);
}
pub fn run<M: MyTrait>(my: &M) {
for a in my {
println!("{}", a);
}
}我知道错误:
error[E0277]: `&M` is not an iterator
--> src/lib.rs:6:14
|
6 | for a in my {
| ^^ `&M` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&M`
= note: required because of the requirements on the impl of `IntoIterator` for `&M`
= note: required by `into_iter`发布于 2021-04-02 14:32:50
只有M实现了IntoIterator,但是您正在尝试在&M上迭代,而这并不是必须的。
还不清楚您希望通过run实现什么,但是删除引用可能是一个开始:
pub fn run<M: MyTrait>(my: M) {
for a in my {
println!("{}", a);
}
}请注意,M本身可能是(或包含)一个引用,因此以这种方式编写它并不意味着您不能将它与借来的数据一起使用。下面是一种使用run在&Vec (游乐场)上迭代的方法:
impl<I> MyTrait for I
where
I: IntoIterator<Item = i32>,
{
fn foo(&self) {}
}
fn main() {
let v = vec![10, 12, 20];
run(v.iter().copied());
}这使用.copied()将Iterator<Item = &i32>转换为Iterator<Item = i32>。
相关问题
https://stackoverflow.com/questions/66919186
复制相似问题