Explores the challenge of returning an `impl Iterator<Item = u32>` from a function that owns an `Rc<Vec<u32>>`. The core problem is that `Rc` only provides shared ownership, so references into the vector cannot outlive the local `Rc` variable. The post explains why naive approaches fail (borrow checker errors due to deterministic drops), presents a working solution using a `move` closure with index-based access, and discusses why returning borrowed references via `Iterator` is fundamentally impossible given the trait's design. It also speculates on future language extensions like self-referential structs and auxiliary return values that could make such patterns more ergonomic.

12m read timeFrom smallcultfollowing.com
Post cover image
Table of contents
The goalFirst draftiter() borrows the collection it is iterating overdrops in Rust are deterministicWhat is the fundamental problem here?How can we fix it?What about if I don’t have integers?How could we extend the language to help here?DiscussionFootnotes