Cloning iterators behind dyn Boxes
⚓ Rust 📅 2026-06-25 👤 surdeus 👁️ 1I posted about this in the Rust discord, but I did not get any replies, so I thought posting here might be a better venue.
I have an iterator that I want to iterate over one of two things, and reuse its values multiple times.
This works, however I have to redo this after every usage:
let mut fov_iter: Box<dyn Iterator<Item = (u16, u16)>> = match full_vision {
true => Box::new(grid_it_all.clone()),
false => Box::new(grid_it_fov.clone()),
};
I could collect the iterator and in most use cases that is probably the best decision, and it's what I've changed my code to do but just for sake of example, e.g. where the full collect may be too large, I'd rather know how to clone the starting iterator behind the box.
I'd like to just directly clone the box and have that clone the underlying iterator, so I found the dyn-clone library and now I have
use dyn_clone::DynClone;
trait PosIterator: DynClone + Iterator<Item = (u16, u16)> {}
dyn_clone::clone_trait_object!(PosIterator);
#[derive(Clone)]
struct MyPosIterator {
iter: Box<dyn PosIterator>,
}
But the iterator I'm creating is coming from a range with flat map, filter, etc applied, and does not implement PosIterator.
How do I do this?
In general, is it possible to implement additional traits on an iterator? or something like a 'newtrait pattern'? For example, augmenting the output of a range, or a flat map.
Iterator is a trait, not a type, which was leading me to a bigger question:
There may not be more than one non-auto trait [...]
Why can trait objects not implement more than one non-auto trait, when function signatures can have multiple trait bounds in an additive combination?
2 posts - 2 participants
🏷️ Rust_feed