#Cloned Iterator to references

14 messages · Page 1 of 1 (latest)

rancid mason
#

Hey Guys!
I dont know how i could create an interator using std that clones another iterator, so it owns the values, but it should return the values as borrows.
I need this as i have an trait function that is supposed to return a boxed iterator that gives a referenced values of some specific type Box<dyn DoubleEndedIterator<Item = &MyValue + 'a>.
Some implementations are supposed to be able to return an iterator over some collection f.e. that is owned by the struct that implements the trait.
And some implementations are supposed to be able to return an iterator that owns these values as the collection might needs to be created "on demand".
I still want to support the former version to make it as optimized as possible without the need to clone the values.

So I can f.e. do something like:

fn foo<'a>() -> Box<dyn DoubleEndedIterator<Item = &MyValue + 'a>> {
  vec![val1.clone(), val2.clone()].into_iter().give_me_refs()
}```
icy saffron
#

Make an iterator over values instead

rancid mason
icy saffron
#

You can’t pull references out if there’s nothing they reference

rancid mason
#

is there no iterator that also owns the values?

worldly dawn
#

There is, but how would you borrow values from it? You cannot access the items without consuming them.

rancid mason
#

thats fine if then consumes the values from the iterator...
just not from the original vector (the one NOT created on demand)

worldly dawn
#

It's not fine if you plan to borrow from that iterator. You have to have some sort of backing collection to borrow from.

lean copper
#

items returned by an iterator can't borrow from the iterator itself

forest tapir
#

You can get around this with something like vec.iter() or vec.iter_mut(), which will iterate through references to the Vec.

#

Since the Vec is not contained within the iterator, you no longer have the mentioned conflict.