Creating an own iterator
When you create an infinitely applicable algorithm or a collection-like structure, it's really nice to have the dozens of methods that an iterator provides at your disposal. For this, you will have to know how to tell Rust to implement them for you.
How to do it...
- In the folder
src/bin
, create a file calledown_iterator.rs
. - 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 ...