我想实现Iterator包含可迭代字段的结构的特征。迭代我的结构应该产生与迭代该字段获得的相同结果。这就是我想要的(显然不起作用):
struct Foo {
bar: Vec<char>,
}
impl Iterator for Foo {
type Item: &char; // Error: expected named lifetime parameter
fn next(&mut self) -> Option<Self::Item> {
self.bar.iter().next()
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免该错误,我尝试插入生命周期:
use std::marker::PhantomData;
struct Foo<'a> {
bar: Vec<char>,
phantom: &'a PhantomData<char> // not sure what to put inside < .. >
}
impl<'a> Iterator for Foo<'a> {
type Item = &'a char;
fn next(&mut self) -> Option<Self::Item> {
self.bar.iter().next() // again, several errors about lifetimes
}
}
Run Code Online (Sandbox Code Playgroud)
我如何实现 …