Skip to content

docs: clarify iterator return types in Chapter 13.3 - #4862

Open
saranshhalwai wants to merge 1 commit into
rust-lang:mainfrom
saranshhalwai:docs/ch13-iterator-return-types
Open

saranshhalwai wants to merge 1 commit into
rust-lang:mainfrom
saranshhalwai:docs/ch13-iterator-return-types

Conversation

@saranshhalwai

Copy link
Copy Markdown

Summary

Chapter 13.3 suggests returning an iterator from search() instead of collecting the results into a vector. Sounds simple enough, except following that suggestion breaks the existing run() implementation.

I followed the instructions and promptly got screwed over by E0308.

The problem is that run() uses an if/else expression to choose between search() and search_case_insensitive(). Changing only one function leaves the branches returning different types. Changing both to return impl Iterator doesn't help either, since Rust treats each opaque return type as distinct.

There's also the lifetime issue introduced by capturing query in the returned iterator.

Changes

  • Explain why the existing if/else expression stops compiling.
  • Clarify why two functions returning impl Iterator<Item = &'a str> don't necessarily return compatible types.
  • Suggest moving the iteration into the individual branches.
  • Mention the lifetime adjustment needed for query.

This is a documentation-only change. No existing examples or functionality have been modified.

Motivation

The book explicitly encourages readers to try this optimization, but doesn't mention that doing so requires changes elsewhere in the project.

I ran into this while working through the book, and it took me a while to figure out why two seemingly identical iterator return types weren't compatible.

Figured the next person shouldn't have to discover this through a compiler error.

Fixes #4518

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Chapter 13.03 change return type to iterator

1 participant