1 // Rust-101, Part 09: Iterators
2 // ============================
9 idx: usize, // the index of the last number that was returned
12 // Now we are equipped to implement `Iterator` for `Iter`.
13 impl<'a> Iterator for Iter<'a> {
14 // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
17 fn next(&mut self) -> Option<u64> {
18 // First, check whether there's any more digits to return.
20 // We already returned all the digits, nothing to do.
23 // Otherwise: Decrement, and return next digit.
29 // All we need now is a function that creates such an iterator for a given `BigInt`.
31 fn iter(&self) -> Iter {
36 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
38 let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
39 for digit in b.iter() {
40 println!("{}", digit);
44 // Of course, we don't have to use `for` to apply the iterator. We can also explicitly call `next`.
45 fn print_digits_v1(b: &BigInt) {
46 let mut iter = b.iter();
48 // Each time we go through the loop, we analyze the next element presented by the iterator - until it stops.
53 fn print_digits_v2(b: &BigInt) {
54 let mut iter = b.iter();
55 while let Some(digit) = iter.next() {
60 // **Exercise 09.1**: Write a testcase for the iterator, making sure it yields the corrects numbers.
62 // **Exercise 09.2**: Write a function `iter_ldf` that iterators over the digits with the least-significant
63 // digits coming first. Write a testcase for it.
65 // ## Iterator invalidation and lifetimes
67 fn iter_invalidation_demo() {
68 let mut b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
69 for digit in b.iter() {
70 println!("{}", digit);
71 /*b = b + BigInt::new(1);*/ /* BAD! */
75 // ## Iterator conversion trait
77 impl<'a> IntoIterator for &'a BigInt {
79 type IntoIter = Iter<'a>;
80 fn into_iter(self) -> Iter<'a> {
84 // With this in place, you can now replace `b.iter()` in `main` by `&b`. Go ahead and try it! <br/>