Iteration (Scoped Effect)

Feature Status

The Iterator trait has been stable in Rust since 1.0, but the generator syntax is currently unstable. This document will assume that generators are created with the gen keyword, but that's for illustrative purposes only.

Description

todo

Technical Overview

PositionSyntax
Effectgen
Yieldyield
ApplyN/A
Consumefor..in
Reificationimpl Iterator

Refinements

ModifierDescription
stepHas a notion of successor and predecessor operations.
trusted len †Reports an accurate length using size_hint.
trusted stepUpholds all invariants of Step.
double-endedIs able to yield elements from both ends.
exact size †Knows its exact length.
fusedAlways continues to yield None when exhausted.

† The difference between TrustedLen and ExactSizeIterator is that TrustedLen is marked as unsafe to implement while ExactSizeIterator is marked as safe to implement. This means that if TrustedLen is implemented, you can rely on it for safety purposes, while with ExactSizeIterator you cannot.

Positions Available

PositionAvailableExample
Manual trait implimpl Iterator for Cat {}
Free functionsgen fn meow() {}
Inherent functionsimpl Cat { gen fn meow() {} }
Trait methodstrait Cat { gen fn meow() {} }
Trait declarationsgen trait Cat {}
Block scopeN/A
Argument qualifiersfn meow(cat: impl gen Cat) {}
Dropimpl gen Drop for Cat {}
Closuresgen ǀǀ {}
Iteratorsfor cat in cats {}

Interactions with other effects

Asynchrony

OverviewDescription
Compositioniterator of futures
DescriptionCreates an iterator of futures. The future takes the iterator by &mut self, so only a single future may be executed concurrently
ExampleAsyncIterator
Implementable as of Rust 1.70?No, async functions in traits are unstable

Fallibility

OverviewDescription
Compositioniterator of tryables
DescriptionCreates an iterator of tryables, typically an iterator of Result
ExampleFallibleIterator
Implementable as of Rust 1.70?No, try in traits is not available

Compile-time Execution

OverviewDescription
Compositionconst iterator
DescriptionCreates an iterator which can be iterated over at compile-time
ExampleN/A
Implementable as of Rust 1.70?No, const traits are unstable

Thread-Safety

OverviewDescription
Compositioniterator of tryables
DescriptionCreates an iterator whose items which can be sent across threads
Examplewhere I: Iterator<Item = T>, T: Send
Implementable as of Rust 1.70?Yes, as a bound on use. And by unit-testing the Send auto-trait on decls.

Immovability

OverviewDescription
Compositionan iterator which takes self: Pin<&mut Self>
DescriptionAn iterator which itself holds onto self-referential data
ExampleN/A
Implementable as of Rust 1.70?Yes

Unwinding

OverviewDescription
Compositioniterator may panic instead of yield
DescriptionCreates an iterator which may panic
ExampleIterator (may panic by default)
Implementable as of Rust 1.70?Yes, but cannot opt-out of "may panic" semantics