如题所示,代码如下:
struct Fib{
a:i32,b:i32,
}
impl Iterator for Fib{
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
let m = self.a;
self.a = self.b;
self.b = self.a + m;
Some(m)
}
}
fn main(){
let fib = Fib{a:0, b:1};
for e in fib.take(7){
//println!("{}", e);//输出每一项
}
let fib = Fib{a:0, b:1};
let fibvec:Vec<_> = fib.take(7).collect();
//输出[0, 1, 1, 2, 3, 5, 8]
println!("{:?}", fibvec);
}