问题描述
在下面的示例中,MyTrait
扩展了 IntoIterator
,但在循环中使用时编译器无法识别它.
In the following example, MyTrait
extends IntoIterator
but the compiler doesn't recognize it when used in a loop.
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`
推荐答案
只有 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>
.
- 为什么借用范围不是迭代器,但范围是?
- 我是否错误地实现了 IntoIterator 以供参考,还是应该报告 Rust 错误?
- 如何为一个简单的结构体实现 Iterator 和 IntoIterator?
- 将 &T 的迭代器收集到 T 的集合中的惯用方法是什么?
- 如何正确地将迭代器传递给 Rust 中的函数
这篇关于为什么我会收到错误“未实现特征‘迭代器’"?对泛型类型的引用,即使它实现了 IntoIterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!