Rust进阶(5)-迭代器

迭代器

概述

  1. 迭代器负责遍历序列中的每一项和决定序列何时结束的逻辑
  2. 创建迭代器:迭代器是惰性的,意思就是在调用方法使用迭代器之前,不会有任何效果
  3. 每个迭代器都实现了iterator trait,iterator trait定义在标准库中:
1
2
3
4
5
//next是Iterator被要求实现的唯一一个方法,next一次返回一个元素,当迭代器结束时,返回None
trait Iterator{
type Item;
fn next(mut self) -> Option<Self::Item>; //type Item和Self::Item这种用法叫做定义trait的关联类型
}

基本使用

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
fn main() {
let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter(); //到目前为止,不会对v1产生任何影响
/*for val in v1_iter{
println!("val = {}", val)
}*/

if let Some(v) = v1_iter.next() {
println!("v = {}", v);//1
}
if let Some(v) = v1_iter.next() {
println!("v = {}", v);//2
}
if let Some(v) = v1_iter.next() {
println!("v = {}", v);//3
}
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(); //调用消费适配器sum来求和
println!("total = {}", total);

//迭代适配器
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,12, 45];
println!("v1 = {:?}", v1);
let v2: Vec<_> = v1.into_iter().filter(|x| *x>5).collect();
println!("v2 = {:?}", v2);
}

自定义迭代器

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
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;
}
}
}

总结

本文编辑完毕

参考

[1] Rust 程序设计语言

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信