I recently discovered std::cell::Ref::map, which is a wonderful function for creating accessors for data inside a RefCell. I am now wondering if there is any way to get an impl Iterator out of a RefCell in some way. I'm running into trouble due to the fact that although Ref implements Deref into an Iterator type, that doesn't make the Ref itself an Iterator. Here is a playground version of my attempt at this.
Any idea how I could achieve this? Obviously, I could return a Ref<ExplicitIteratorType>, but that leaks my implementation (and has a very long type), or requires me to create a wrapper struct, which is also a nuisance.
A Ref<impl Iterator<Item = ...>> is useless, because all iterators need to be mutable to run Iterator::next, so I will assume you will change that to RefMut<impl Iterator<Item = ...>>. Now, you could just get a &mut out of the RefMut, and a mutable reference to an iterator is also an iterator. This can be done as shown below.
this impl Iterator is not valid, I am just using it as a palceholder for your RefMut
let ref_mut : std::cell::RefMut<'_, impl Iterator> = ...;
let iter : &mut _ = &mut *ref_mut;
Yeah, I see there are several problems with my solution (and with my "obviousl I could" alternative. Right now I can see no way to create an Iterator to an object in a RefCell short of creating a custom struct to hold a Ref.
Is there any way to return an iterator to an object held in a RefCell?
I could use callbacks, but that would defeat the goal of providing a standard and familiar interface. Worst case scenario would be a wrapper struct that holds a Ref and a usizeIterator. It's a little inefficient to do bounds checks, but would beat a callback approach in both efficiency and ease of use.
It's disappointing that we don't seem to have a zero cost abstraction for this use case.
Actually, now that I look at this again, this isn't much better than just returning a RefMut, so I don't have a good solution short of using unsafe code.