rustbook_learning_guide/
iterators.rs

1//! Iterator examples
2
3pub fn iterator_examples() {
4    println!("\nšŸ”„ Iterator Examples");
5    println!("{}", "-".repeat(21));
6    
7    let vec = vec![1, 2, 3, 4, 5];
8    let doubled: Vec<i32> = vec.iter().map(|x| x * 2).collect();
9    println!("Doubled: {:?}", doubled);
10    
11    let sum: i32 = vec.iter().sum();
12    println!("Sum: {}", sum);
13}
14
15pub fn manual_iterator_demo() {
16    println!("\nšŸ”§ Manual Iterator Demo");
17    println!("{}", "-".repeat(25));
18    
19    struct Counter {
20        current: usize,
21        max: usize,
22    }
23    
24    impl Counter {
25        fn new(max: usize) -> Counter {
26            Counter { current: 0, max }
27        }
28    }
29    
30    impl Iterator for Counter {
31        type Item = usize;
32        
33        fn next(&mut self) -> Option<Self::Item> {
34            if self.current < self.max {
35                let current = self.current;
36                self.current += 1;
37                Some(current)
38            } else {
39                None
40            }
41        }
42    }
43    
44    let counter = Counter::new(3);
45    for num in counter {
46        println!("Count: {}", num);
47    }
48}
49
50pub use crate::smart_pointers::{Shoe, shoes_in_size};
51