X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/66c777f23e032d445e29b1b40faa8e1799b4930c..d5cee5ca7d257faea7f68b8812bf4d1a88ab5229:/workspace/src/part09.rs?ds=inline diff --git a/workspace/src/part09.rs b/workspace/src/part09.rs index d6b8bba..61cc70b 100644 --- a/workspace/src/part09.rs +++ b/workspace/src/part09.rs @@ -1,26 +1,10 @@ -// Rust-101, Part 09: Iterators (WIP) -// ================================== +// Rust-101, Part 09: Iterators +// ============================ use part05::BigInt; -// In the following, we will look into the iterator mechanism of Rust and make our `BigInt` compatible -// with the `for` loops. Of course, this is all about implementing particular traits again. In particular, -// 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), -// this trait mandates a single function `next` returning an `Option`, where `Item` is an -// associated type chosen by the implementation. (There are many more methods provided for `Iterator`, -// but they all have default implementations, so we don't have to worry about them right now). -// -// For the case of `BigInt`, we want our iterator to iterate over the digits in normal, notational order: The most-significant -// digit comes first. So, we have to write down some type, and implement `Iterator` for it such that `next` returns the digits -// one-by-one. Clearly, the iterator must somehow be able to access the number it iterates over, and it must store its current -// location. However, it cannot *own* the `BigInt`, because then the number would be gone after iteration! That'd certainly be bad. -// The only alternative is for the iterator to *borrow* the number. - -// In writing this down, we again have to be explicit about the lifetime of the borrow: We can't just have an -// `Iter`, we must have an `Iter<'a>` that borrowed the number for lifetime `'a`.
-// `usize` here is the type of unsigned, pointer-sized numbers. It is typically the type of "lengths of things", -// 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. -struct Iter<'a> { + +pub struct Iter<'a> { num: &'a BigInt, idx: usize, // the index of the last number that was returned } @@ -33,10 +17,10 @@ impl<'a> Iterator for Iter<'a> { fn next(&mut self) -> Option { // First, check whether there's any more digits to return. if self.idx == 0 { - // We already returned all the digits. + // We already returned all the digits, nothing to do. unimplemented!() } else { - // Decrement, and return next digit. + // Otherwise: Decrement, and return next digit. unimplemented!() } } @@ -44,9 +28,6 @@ impl<'a> Iterator for Iter<'a> { // All we need now is a function that creates such an iterator for a given `BigInt`. impl BigInt { - // 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 - // the case with functions returning borrowed data, you can elide the lifetime. The rules for adding the lifetimes are exactly the - // same. (See the last section of [part 06](part06.html).) fn iter(&self) -> Iter { unimplemented!() } @@ -60,3 +41,45 @@ pub fn main() { } } +// Of course, we don't have to use `for` to apply the iterator. We can also explicitly call `next`. +fn print_digits_v1(b: &BigInt) { + let mut iter = b.iter(); + loop { + // Each time we go through the loop, we analyze the next element presented by the iterator - until it stops. + unimplemented!() + } +} + +fn print_digits_v2(b: &BigInt) { + let mut iter = b.iter(); + while let Some(digit) = iter.next() { + println!("{}", digit) + } +} + +// **Exercise 09.1**: Write a testcase for the iterator, making sure it yields the corrects numbers. +// +// **Exercise 09.2**: Write a function `iter_ldf` that iterators over the digits with the least-significant +// digits coming first. Write a testcase for it. + +// ## Iterator invalidation and lifetimes + +fn iter_invalidation_demo() { + let mut b = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63); + for digit in b.iter() { + println!("{}", digit); + /*b = b + BigInt::new(1);*/ /* BAD! */ + } +} + +// ## Iterator conversion trait + +impl<'a> IntoIterator for &'a BigInt { + type Item = u64; + type IntoIter = Iter<'a>; + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} +// With this in place, you can now replace `b.iter()` in `main` by `&b`. Go ahead and try it!
+