创建Iterator 的东西和创建Iterator 的东西之间有很大的不同。例如,Vec<char> 可以产生一个迭代器,但它本身不是一个迭代器。这里有两个简单的例子,希望您能找到适合您用例的东西。
生成迭代器
根据您的情况,最简单的方法是为该字段实现Deref,然后让Vec<char> 处理它。或者,您可以为bar.iter() 编写一个包装函数。
pub struct Foo {
bar: Vec<char>,
}
impl Deref for Foo {
type Target = Vec<char>;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
let foo = Foo { bar: vec!['a', 'b', 'c', 'd'] };
// deref is implicitly called so foo.iter() represents foo.bar.iter()
for x in foo.iter() {
println!("{:?}", x);
}
编写迭代器
以下是您如何为Vec<char> 编写自己的迭代器。请注意 Vec 如何存储为引用而不是拥有的值。这使得 rust 可以解决生命周期的限制。通过在迭代器的生命周期内持有一个不可变的引用,我们保证由该迭代器产生的引用也可以在该生命周期内持续存在。如果我们使用拥有的值,我们只能保证元素引用的生命周期持续到下一次对迭代器进行可变引用。或者换句话说,每个值只能持续到再次调用next。然而,即使这样也需要夜间功能才能正确表达。
pub struct SimpleIter<'a> {
values: &'a Vec<char>,
index: usize,
}
impl<'a> Iterator for SimpleIter<'a> {
type Item = &'a char;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.values.len() {
return None
}
self.index += 1;
Some(&self.values[self.index - 1])
}
}
这是一个通用迭代器包装另一个迭代器的简单示例。
// Add ?Sized so Foo can hold a dynamically sized type to satisfy IntoFoo
struct Foo<I: ?Sized> {
bar: I,
}
impl<I: Iterator> Iterator for Foo<I> {
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
println!("Iterating through Foo");
self.bar.next()
}
}
您还可以通过创建一个易于使用Foo 的特征来获得更多花哨的功能。
pub trait IntoFoo {
fn iter_foo(self) -> Foo<Self>;
}
// Add an iter_foo() method for all existing iterators
impl<T: Iterator> IntoFoo for T {
fn iter_foo(self) -> Foo<Self> {
Foo { bar: self }
}
}
let values = vec!['a', 'b', 'c', 'd'];
// Get default iterator and wrap it with our foo iterator
let foo: Foo<std::slice::Iter<'_, char>> = values.iter().iter_foo();
for x in foo {
println!("{:?}", x);
}