1 // Rust-101, Part 09: Iterators
2 // ============================
6 //@ In the following, we will look into the iterator mechanism of Rust and make our `BigInt`
7 //@ compatible with the `for` loops. Of course, this is all about implementing certain traits
8 //@ again. In particular, an iterator is something that implements the `Iterator` trait. As you can
9 //@ see in the [documentation](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html), this
10 //@ trait mandates a single function `next` returning an `Option<Self::Item>`, where `Item` is an
11 //@ associated type chosen by the implementation. (There are many more methods provided for
12 //@ `Iterator`, but they all have default implementations, so we don't have to worry about them
15 //@ For the case of `BigInt`, we want our iterator to iterate over the digits in normal, notational
16 //@ order: The most-significant digit comes first. So, we have to write down some type, and
17 //@ implement `Iterator` for it such that `next` returns the digits one-by-one. Clearly, the
18 //@ iterator must somehow be able to access the number it iterates over, and it must store its
19 //@ current location. However, it cannot *own* the `BigInt`, because then the number would be gone
20 //@ after iteration! That'd certainly be bad. The only alternative is for the iterator to *borrow*
21 //@ the number, so it takes a reference.
22 //@ In writing this down, we again have to be explicit about the lifetime of the reference: We
23 //@ can't just have an `Iter`, we must have an `Iter<'a>` that borrows the number for lifetime
24 //@ `'a`. This is our first example of a data-type that's polymorphic in a lifetime, as opposed to
26 //@ `usize` here is the type of unsigned, pointer-sized numbers. It is typically the type of
27 //@ "lengths of things", in particular, it is the type of the length of a `Vec` and hence the right
28 //@ type to store an offset into the vector of digits.
32 idx: usize, // the index of the last number that was returned
35 // Now we are equipped to implement `Iterator` for `Iter`.
36 impl<'a> Iterator for Iter<'a> {
37 // We choose the type of things that we iterate over to be the type of digits, i.e., `u64`.
40 fn next(&mut self) -> Option<u64> {
41 // First, check whether there's any more digits to return.
43 // We already returned all the digits, nothing to do.
46 // Otherwise: Decrement, and return next digit.
47 self.idx = self.idx - 1; /*@*/
48 Some(self.num.data[self.idx]) /*@*/
53 // All we need now is a function that creates such an iterator for a given `BigInt`.
55 //@ Notice that when we write the type of `iter`, we don't actually have to give the lifetime
56 //@ parameter of `Iter`. Just as it is the case with functions returning references, you can
57 //@ elide the lifetime. The rules for adding the lifetimes are exactly the same. (See the last
58 //@ section of [part 06](part06.html).)
59 fn iter(&self) -> Iter {
60 Iter { num: self, idx: self.data.len() } /*@*/
64 // We are finally ready to iterate! Remember to edit `main.rs` to run this function.
66 let b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
67 for digit in b.iter() {
68 println!("{}", digit);
72 // Of course, we don't have to use `for` to apply the iterator. We can also explicitly call `next`.
73 fn print_digits_v1(b: &BigInt) {
74 let mut iter = b.iter();
75 //@ `loop` is the keyword for a loop without a condition: It runs endlessly, or until you break
76 //@ out of it with `break` or `return`.
78 // Each time we go through the loop, we analyze the next element presented by the iterator
80 match iter.next() { /*@*/
82 Some(digit) => println!("{}", digit) /*@*/
87 //@ Now, it turns out that this combination of doing a loop and a pattern matching is fairly
88 //@ common, and Rust provides some convenient syntactic sugar for it.
89 fn print_digits_v2(b: &BigInt) {
90 let mut iter = b.iter();
91 //@ `while let` performs the given pattern matching on every round of the loop, and cancels the
92 //@ loop if the pattern doesn't match. There's also `if let`, which works similar, but of
93 //@ course without the loopy part.
94 while let Some(digit) = iter.next() {
99 // **Exercise 09.1**: Write a testcase for the iterator, making sure it yields the corrects numbers.
101 // **Exercise 09.2**: Write a function `iter_ldf` that iterates over the digits with the
102 // least-significant digits coming first. Write a testcase for it.
104 // ## Iterator invalidation and lifetimes
105 //@ You may have been surprised that we had to explicitly annotate a lifetime when we wrote `Iter`.
106 //@ Of course, with lifetimes being present at every reference in Rust, this is only consistent.
107 //@ But do we at least gain something from this extra annotation burden? (Thankfully, this burden
108 //@ only occurs when we define *types*, and not when we define functions - which is typically much
111 //@ It turns out that the answer to this question is yes! This particular aspect of the concept of
112 //@ lifetimes helps Rust to eliminate the issue of *iterator invalidation*. Consider the following
114 fn iter_invalidation_demo() {
115 let mut b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
116 for digit in b.iter() {
117 println!("{}", digit);
118 /*b = b + BigInt::new(1);*/ /* BAD! */
122 //@ If you enable the bad line, Rust will reject the code. Why? The problem is that we are
123 //@ modifying the number while iterating over it. In other languages, this can have all sorts of
124 //@ effects from inconsistent data or throwing an exception (Java) to bad pointers being
125 //@ dereferenced (C++). Rust, however, is able to detect this situation.
126 //@ When you call `iter`, you have to borrow `b` for some lifetime `'a`, and you obtain `Iter<'a>`.
127 //@ This is an iterator that's only valid for lifetime `'a`. Gladly, we have this annotation
128 //@ available to make such a statement. Rust enforces that `'a` spans every call to `next`, which
129 //@ means it has to span the loop.
130 //@ Thus `b` is borrowed for the duration of the loop, and we cannot mutate it. This is yet another
131 //@ example for how the combination of mutation and aliasing leads to undesired effects (not
132 //@ necessarily crashes, think of Java), which Rust successfully prevents.
134 // ## Iterator conversion trait
135 //@ If you closely compare the `for` loop in `main` above, with the one in `part06::vec_min`, you
136 //@ will notice that we were able to write `for e in v` earlier, but now we have to call `iter`.
137 //@ Why is that? Well, the `for` sugar is not actually tied to `Iterator`. Instead, it demands an
138 //@ implementation of
139 //@ [`IntoIterator`](https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html).
140 //@ That's a trait of types that provide a *conversion* function into some kind of iterator. These
141 //@ conversion traits are a frequent pattern in Rust: Rather than demanding that something is an
142 //@ iterator, or a string, or whatever; one demands that something can be converted to an
143 //@ iterator/string/whatever. This provides convenience similar to overloading of functions: The
144 //@ function can be called with lots of different types.
145 //@ By implementing such traits for your types, you can even make your own types work smoothly with
146 //@ existing library functions. As usually for Rust, this abstraction comes at zero cost: If your
147 //@ data is already of the right type, the conversion function will not do anything and trivially
148 //@ be optimized away.
150 //@ If you have a look at the documentation of `IntoIterator`, you will notice that the function
151 //@ `into_iter` it provides actually consumes its argument. So we implement the trait for
152 //@ *references to* numbers, such that the number is not lost after the iteration.
153 impl<'a> IntoIterator for &'a BigInt {
155 type IntoIter = Iter<'a>;
156 fn into_iter(self) -> Iter<'a> {
160 // With this in place, you can now replace `b.iter()` in `main` by `&b`. Go ahead and try it! <br/>
162 //@ Wait, `&b`? Why that? Well, we implemented `IntoIterator` for `&BigInt`. If we are in a place
163 //@ where `b` is already borrowed, we can just do `for digit in b`. If however, we own `b`, we have
164 //@ to create a reference to it. Alternatively, we could implement `IntoIterator` for `BigInt` -
165 //@ which, as already mentioned, would mean that `b` is actually consumed by the iteration, and
167 //@ This can easily happen, for example, with a `Vec`: Both `Vec` and `&Vec` (and `&mut Vec`)
168 //@ implement `IntoIterator`, so if you do `for e in v`, and `v` has type `Vec`, then you will
169 //@ obtain ownership of the elements during the iteration - and destroy the vector in the process.
170 //@ We actually did that in `part01::vec_min`, but we did not care. You can write `for e in &v` or
171 //@ `for e in v.iter()` to avoid this.
173 //@ [index](main.html) | [previous](part08.html) | [raw source](workspace/src/part09.rs) |
174 //@ [next](part10.html)