How to do it...

  1. In the folder src/bin, create a file called own_iterator.rs.
  2. Add the following code, and run it with cargo run --bin own_iterator:
1   fn main() {
2 let fib: Vec<_> = fibonacci().take(10).collect();
3 println!("First 10 numbers of the fibonacci sequence: {:?}",
fib);
4
5 let mut squared_vec = SquaredVec::new();
6 squared_vec.push(1);
7 squared_vec.push(2);
8 squared_vec.push(3);
9 squared_vec.push(4);
10 for (index, num) in squared_vec.iter().enumerate() {
11 println!("{}^2 is {}", index + 1, num);
12 }
13 }
14
15
16 fn fibonacci() -> Fibonacci {
17 Fibonacci { curr: 0, next: 1 }
18 }
19 struct Fibonacci {
20 curr: u32,
21 next: u32,
22 }
23 // A custom iterator has to implement
24 // only one method: What comes next
25 impl Iterator for Fibonacci {
26 type Item = u32;
27 fn next(&mut self) -> Option<u32> {
28 let old = self.curr;
29 self.curr = self.next;
30 self.next += old;
31 Some(old)
32 }
33 }
34
35
36 use std::ops::Mul;
37 struct SquaredVec<T>
38 where
39 T: Mul + Copy,
40 {
41 vec: Vec<T::Output>,
42 }
43 impl<T> SquaredVec<T>
44 where
45 T: Mul + Copy,
46 {
47 fn new() -> Self {
48 SquaredVec { vec: Vec::new() }
49 }
50 fn push(&mut self, item: T) {
51 self.vec.push(item * item);
52 }
53 }
54
55 // When creating an iterator over a collection-like struct
56 // It's best to just allow it to be convertible into
57 // a slice of your underlying type.
58 // This way you automatically implemented a bunch of methods
59 // and are flexible enough to change your implementation later
on
60 use std::ops::Deref;
61 impl<T> Deref for SquaredVec<T>
62 where
63 T: Mul + Copy,
64 {
65 type Target = [T::Output];
66 fn deref(&self) -> &Self::Target {
67 &self.vec
68 }
69 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.202