頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
1、實現Iterator trait來建立自定義迭代器
例子:
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
//實現自定義迭代器
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.count += 1;
if self.count < 6 {
Some(self.count)
} else {
None
}
}
}
//使用
fn main() {
let mut counter = Counter::new();
for i in (0..6) {
if let Some(v) = counter.next() {
println!("i = {}, v = {}", i, v);
} else {
println!("i = {}, at end", i);
break;
}
}
}
2、迭代器並不會引入其它的效能開銷
本作品採用《CC 協議》,轉載必須註明作者和本文連結