Apologies for the country song subject line, but I think it's kind of catchy!
My problem has a solution that will be obvious to anyone not me. It will probably even be obvious to me, by tomorrow...
At a high level, I want a trait that has an iter()
method that returns an Iterator over references. I was surprised to not find a trait for iter()
in the standard library; only IntoIter is supported. But that is to return values, not references.
My first attempt looks like so: Rust Playground
The relevant code being
trait MyTrait<T> {
fn iter(&self) -> Iterator<Item = &T>;
}
and
impl<T> MyTrait<T> for MyStruct<T> {
fn iter(&self) -> MyStructIterator<T> {
MyStructIterator::new(&self.elements)
}
}
The compile error says it all; my trait returns an Iterator
, but my implementation of that trait returns a specific struct named MyStructIterator
(I'm very imaginative in naming). Though MyStructIterator
implements Iterator, Rust doesn't seem to know that. I've tried returning Iterator, but the compiler doesn't like that, and I tried some permutations of putting dyn
and impl
in the trait definition and the method implementation, but I didn't know what I was doing.
My second attempt was to "do it just like IntoIterator": Rust Playground
This also almost worked, but again, the compiler didn't like this bit:
impl<'a, T> MyTrait<T> for MyStruct<T> {
type Item = T;
type MyIter = MyStructIterator<'a, T>;
fn iter(&self) -> MyStructIterator<T> {
MyStructIterator::new(&self.elements)
}
}
The lifetime 'a
isn't anchored to anything, and I don't know how to satisfy it.
So the question is: Am I getting close?