Iter<T> -> Iter<&T>?

Given an Iter<T> is there a way to build a Iter<&T>? I've looked at Iter in std::slice - Rust but see nothing obvious.

No*, that would require some sort of streaming iterator.

* you can collect the items into a Vec<T>, then call iter to get an iterator over &T

1 Like

For my mental models, can we construct a situation where bad things happen if Iter<T> -> Iter<&T> exited for arbitrary T ?

My mental intuition for why this should be safe is:

Imagine A is the consumer of Iter<&T>
Here's what B can do. B takes a Iter<T>, consumes an element on demand, and passes a ref to A.
Then, when A wants the next elem, B frees up the old one ... hmm <-- is this where this beaks down? B can't know when to "free" the existing element -- so we end up with either (1) memory leak due to keeping all the T's around or (2) potentially unsafe/dangling ref's ?

Remember that for all iterators this is valid and must be supported:

let a =;
let b =;
use_both(a, b);

Exactly, you can never be sure when to free them in the normal iterator interface. With streaming iterators, you can free them on the next element, but not with normal iterators.

1 Like

Yep, just like streaming_iterator::convert.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.