rust-lang / book

The Rust Programming Language
https://doc.rust-lang.org/book/
Other
15k stars 3.39k forks source link

swap two sentences in 13-12 to complete the discussion of immutable vs mutable iterators before introducing into_iter #3951

Closed bkc closed 3 months ago

bkc commented 3 months ago

URL to the section(s) of the book with this problem: https://github.com/rust-lang/book/blob/main/src/ch13-02-iterators.md

Description of the problem:

In the paragraph immediately preceding level 3 header "Methods that Consume the Iterator" (around lines 95 to 100), the paragraph discusses immutable iterators, jumps to iterators that take ownership, then back to mutable iterators.

Also note that the values we get from the calls to next are immutable references to the values in the vector. The iter method produces an iterator over immutable references. If we want to create an iterator that takes ownership of v1 and returns owned values, we can call into_iter instead of iter. Similarly, if we want to iterate over mutable references, we can call iter_mut instead of iter.

Would it be helpful to complete the comparison of immutable vs mutable iterators before mentioning iterators that take ownership?

Suggested fix:

Also note that the values we get from the calls to next are immutable references to the values in the vector. The iter method produces an iterator over immutable references. If we want to iterate over mutable references, we can call iter_mut instead of iter. Similarly, if we want to create an iterator that takes ownership of v1 and returns owned values, we can call into_iter instead of iter.

chriskrycho commented 3 months ago

Thanks for the suggestion. I think it's actually fine the way it is, though. The current version uses parallelism to describe first immutable and then mutable iterators in both parts: an A-B-A-B approach rather than an A-B-B-A approach (where A = immutable and B = mutable). If we made the change you suggest, it would pull the bits about mutability together, but push the bits about immutable iterators further away from each other—so someone else might show up with the exact opposite suggestion later! Thanks.