- 迭代器负责遍历序列中的每一项和决定序列合适结束的逻辑
- 创建迭代器: 迭代器是惰性的,调用迭代器之前不会有任何效果
- 每个迭代器实现了iterator trait,iterator定义在标准库之中
1 2 3 4 5 6 7 8
| fn main() { let v1 = vec![1,2,3]; let v1_iter = v1.iter(); for val in v1_iter { println!("val = {}",val); } }
|
next 是Iterator被要求实现的惟一一个方法,next一次返回一个元素,
迭代器结束的时候返回None
1 2 3 4 5 6
| trait Iterator { type Item; fn next(mut self) -> Option<Self::Item>; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| fn main() { let v1 = vec![1,2,3]; let mut v1_iter = v1.iter();
if let Some(v) = v1_iter.next() { println!("v = {}",v); } if let Some(v) = v1_iter.next() { println!("v = {}",v); } if let Some(v) = v1_iter.next() { println!("v = {}",v); } if let Some(v) = v1_iter.next() { println!("v = {}",v); } else { println!("At end"); } let mut v2 = vec![1,2,3]; let mut v2_iter = v2.iter_mut(); if let Some(v) = v2_iter.next() { *v = 3; } println!("v2 = {:?}",v2);
let v1 = vec![1,2,3]; let v1_iter = v1.iter(); let total: i32 = v1_iter.sum(); println!("total = {}",total);
println!("++++++++++++++"); let v1 = vec![1,2,3]; println!("v1 = {:?}",v1);
let v2: Vec<_> = v1.iter().map(|x| x+1).collect(); println!("v2 = {:?}",v2); let v1 = vec![1,23,44,3]; let v3: Vec<_> = v1.into_iter().filter(|x| *x>5).collect(); println!("v3 = {}",v3);
}
|