For Advent of Code Day 17 (problem statement isn't super important), what I want to do is have a type:
#[derive(Debug, Clone)]
struct Cubes {
active: HashSet<Vec<i32>>,
}
And create an Iterator
that yields out successive instances of that type. I can (did) implement this:
impl Iterator for Cubes {
type Item = Cubes;
fn next(&mut self) -> Option<Cubes> { ... }
}
Which works fine, but is pretty expensive since what I end up doing is both modifying the Cubes
locally and also returning a copy of it.
What I'd like do is have the Iterator
mutate its internal state and hand out a reference to it, so that I don't need to make any copies.
Even in the most trivial case of like an infinite iterator that just hands out a reference, I can't come up with a formulation of this that checks:
// this doesn't actually compile
fn iter(cc: &mut Cubes) -> impl Iterator<Item=&Cubes> {
std::iter::from_fn(move ||{
Some(&*cc)
})
}
whereas what I'm doing is roughly equivalent to this (which does compile, but I am trying to improve):
fn iter(cc: ConwayCubes) -> impl Iterator<Item=ConwayCubes> {
std::iter::from_fn(move ||{
Some(cc.clone())
})
}
I suppose I could also restructure the problem to hand out something like Rc<Cubes>
, which would still do copies but those copies would be cheap, but I'm curious if there's a way to do this with references.