在下面的示例中,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`
最佳答案
只有 M
工具 IntoIterator
,但您正在尝试迭代 &M
,这不是必须的。
不清楚您希望通过 run
实现什么,但删除引用可能是一个开始:
pub fn run<M: MyTrait>(my: M) {
for a in my {
println!("{}", a);
}
}
请注意 M
本身 可能是(或包含)一个引用,因此以这种方式编写它并不意味着您不能将它与借来的数据一起使用。这是使用 run
的一种方法遍历 &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<Item = &i32>
到Iterator<Item = i32>
.
相关问题
- Why is a borrowed range not an iterator, but the range is?
- Am I incorrectly implementing IntoIterator for a reference or is this a Rust bug that should be reported?
- How to implement Iterator and IntoIterator for a simple struct?
- What is an idiomatic way to collect an iterator of &T into a collection of Ts?
- How to properly pass Iterators to a function in Rust
关于rust - 为什么我会收到错误 "the trait ` Iterator` is not implemented"以引用泛型类型,即使它实现了 IntoIterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66919186/