I have a custom container, for which I want to implement a custom iterator. The container type is described by an interface, as it can have multiple underlying implementations (e.g. vector or tree based).
Currently I have these methods that return a boxed iterator, since we cannot use impl Iterator in trait return types
The reason why I want to make the trait have the iter methods, is because I have other methods on the trait like has_any that I then could implement with default implementations on the trait itself.
Now the iter implementation obviously doesn't work since I cannot move the tags into the Box, but using &self.tags.into_iter() yields a reference and not an iterator.
Is the thing I want to do even possible? Do I need to use nightly, or a completely different approach?
You can put a lifetime on the trait object. By default, in function signatures, trait objects have an implicit + 'static lifetime bound, which means they can't store any references. But we can override that by adding our own bound. In this case, we can use an elided + '_ bound to say that the returned trait object must live as long as the &self or &mut self reference.
The rules are actually slightly more complex, the TL;DR being that Box<dyn Trait> is indeed Box<dyn Trait + 'static>, but &dyn Trait and &mut dyn Trait don't use 'static but the lifetime from the reference, so that &'a dyn Trait is &'a (dyn Trait + 'a) and &'a mut dyn Trait is &'a mut (dyn Trait + 'a).