cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
642 stars 100 forks source link

Chapter 13 Section 2 Question Clarification/Issue #230

Open bmarwritescode opened 4 days ago

bmarwritescode commented 4 days ago

URL to the section(s) of the book with this problem:

https://rust-book.cs.brown.edu/ch13-02-iterators.html

Description of the problem:

On question 2 of the final quiz in Chapter 13 section 2, the following two code snippets are said to be semantically equivalent:

while let Some(x) = iter.next() {
    f(x);
}
for x in iter {
    f(x);
}

However, this might not be the case (depending on how you define semantic equivalence). The second code snippet will fail to compile if iter is a type that does not implement the Iterator trait. The first one, however, will compile as long as that type defines some function next that returns an option. To be explicit, the first will compile but the second will not assuming iter is an instance of the following struct:

struct MyIter {}

impl MyIter {
    fn next(&self) -> Option<u32> {
        None
    }
}

Suggested fix:

Add in an explicit type and/or definition for iter.