1 // Rust-101, Part 09: Iterators (WIP)
2 // ==================================
6 // In the following, we will look into the iterator mechanism of Rust and make our `BigInt` compatible
7 // with the `for` loops. Of course, this is all about implementing particular traits again. In particular,
8 // an iterator is something that implements the `Iterator` trait. As you can see in [the documentation](http://doc.rust-lang.org/beta/std/iter/trait.Iterator.html),
9 // this trait mandates a single function `next` returning an `Option<Self::Item>`, where `Item` is an
10 // associated type chosen by the implementation. (There are many more methods provided for `Iterator`,
11 // but they all have default implementations, so we don't have to worry about them right now).
13 // For the case of `BigInt`, we want our iterator to iterate over the digits in normal, notational order: The most-significant
14 // digit comes first. So, we have to write down some type, and implement `Iterator` for it such that `next` returns the digits
15 // one-by-one. Clearly, the iterator must somehow be able to access the number it iterates over, and it must store its current
16 // location. However, it cannot *own* the `BigInt`, because then the number would be gone after iteration! That'd certainly be bad.
17 // The only alternative is for the iterator to *borrow* the number.
19 // In writing this down, we again have to be explicit about the lifetime of the borrow: We can't just have an
20 // `Iter`, we must have an `Iter<'a>` that borrowed the number for lifetime `'a`. <br/>
21 // `usize` here is the type of unsigned, pointer-sized numbers. It is typically the type of "lengths of things",
22 // in particular, it is the type of the length of a `Vec` and hence the right type to store an offset into the vector of digits.
25 idx: usize, // the index of the last number that was returned
28 // Now we are equipped to implement `Iterator` for `Iter`.
29 impl<'a> Iterator for Iter<'a> {
30 // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
33 fn next(&mut self) -> Option<u64> {
34 // First, check whether there's any more digits to return.
36 // We already returned all the digits.
39 // Decrement, and return next digit.
45 // All we need now is a function that creates such an iterator for a given `BigInt`.
47 // Notice that when we write the type of `iter`, we don't actually have to give the lifetime parameter of `Iter`. Just as it is
48 // the case with functions returning borrowed data, you can elide the lifetime. The rules for adding the lifetimes are exactly the
49 // same. (See the last section of [part 06](part06.html).)
50 fn iter(&self) -> Iter {
55 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
57 let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
58 for digit in b.iter() {
59 println!("{}", digit);