更新时间:2022-06-09 01:05:32
只有 M
实现了 IntoIterator
,但您正在尝试迭代 &M
,这不是必须的.
Only M
implements IntoIterator
, but you're trying to iterate over a &M
, which doesn't have to.
不清楚您希望通过 run
实现什么,但删除引用可能是一个开始:
It's not clear what you hope to achieve with run
, but removing the reference might be a start:
pub fn run<M: MyTrait>(my: M) {
for a in my {
println!("{}", a);
}
}
请注意,M
本身 可能是(或包含)一个引用,因此以这种方式编写它并不意味着您不能将其与借用数据一起使用.这是使用 run
迭代 &Vec
(playground):
Note that M
itself may be (or contain) a reference, so writing it in this way doesn't mean you can't use it with borrowed data. Here's one way to use run
to iterate over a &Vec
(playground):
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
转换为 Iterator
.
This uses .copied()
to turn an Iterator<Item = &i32>
to an Iterator<Item = i32>
.