-
Notifications
You must be signed in to change notification settings - Fork 0
/
27-iterators.rs
55 lines (46 loc) · 1.27 KB
/
27-iterators.rs
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
51
52
53
54
55
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 using_other_iterator_trait_methods() {
let sum:u32 = Counter::new().zip(Counter::new().skip(1)).map(|(a,b)| a*b).filter(|x| x%3 ==0).sum();
assert_eq!(18, sum);
}
fn main() {
let v1 = vec![1,2,3];
let v1_iter=v1.iter();
let mut v1_iter2=v1.iter();
for val in v1_iter {
println!("{}", val)
}
assert_eq!(v1_iter2.next(), Some(&1));
assert_eq!(v1_iter2.next(), Some(&2));
assert_eq!(v1_iter2.next(), Some(&3));
assert_eq!(v1_iter2.next(), None);
let v1:Vec<i32> = vec![1,2,3];
let v2:Vec<_> = v1.iter().map(|x| x + 1).collect();
assert_eq!(v2,vec![2,3,4]);
let mut counter = Counter::new();
assert_eq!(counter.next(), Some(1));
assert_eq!(counter.next(), Some(2));
assert_eq!(counter.next(), Some(3));
assert_eq!(counter.next(), Some(4));
assert_eq!(counter.next(), Some(5));
assert_eq!(counter.next(), None);
using_other_iterator_trait_methods();
}