如何使用 Trait 实现迭代器
我有一个名为 Library 的结构,它有一个字符串向量(标题)。我为此实现了一个迭代器。这是我的代码。
#[derive(Debug, Clone)]
struct Library {
books: Vec<String>
}
impl Iterator for Library {
fn next(&mut self) -> Option<Self::Item> {
...
}
}
现在,我尝试使用特征实现迭代器,如下所示:
fn foo(x: Vec<u32>) -> impl Iterator<Item=u32> {
//Unsure if correct method
fn next() -> Option<...> {
x.into_iter()....
}
}
但我不确定在这种情况下如何继续。我是否只需再次定义 next() 方法?根据其他资源,情况似乎并非如此。这是为什么?迭代器(正在返回)不应该有 next() 方法吗?
以这种方式实现迭代器的一般方法是什么?
I have a struct called Library, which has a vector of strings (titles). I have implemented an iterator for this. Here is my code.
#[derive(Debug, Clone)]
struct Library {
books: Vec<String>
}
impl Iterator for Library {
fn next(&mut self) -> Option<Self::Item> {
...
}
}
Now, I am trying to implement an Iterator using a trait, like this:
fn foo(x: Vec<u32>) -> impl Iterator<Item=u32> {
//Unsure if correct method
fn next() -> Option<...> {
x.into_iter()....
}
}
But I'm unsure of how to proceed in this case. Do I simply have to define a next() method again? That doesn't seem to be the case, according to other resources. Why is that? Shouldn't an iterator (which is being returned) have a next() method?
What is the general method for implementing an iterator this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不会直接在
Library
上实现该特征。该库不是迭代器,但它是可以由迭代器迭代的东西。相反,只需声明一个返回迭代器的方法,您就可以直接从向量返回迭代器。不需要自定义迭代器实现。例如:
对于第二种情况,您可以使用
into_iter()
将向量转换为迭代器,由IntoIterator
特征提供:You wouldn't implement the trait directly on
Library
. The library is not an iterator, but it is something that could be iterated by an iterator.Instead, just declare a method that returns an iterator, and you can simply return an iterator directly from your vector. There is no need for a custom iterator implementation. For example:
For your second case, you can turn the vector into an iterator using
into_iter()
, provided by theIntoIterator
trait: