Hi there,
I'm about to define a trait that contains a method that shall return an Iterator
of some type like so:
pub trait Trait<'a> {
type Iter: Iterator<Item = &'a&'a str>;
fn iter(&self) -> Self::Iter;
}
However, when implementing the trait for a specific type the contents of the type the iter()
method is about to provide are not always of the item type requested - e.g. &&str
in my case. Thus I'd like to use map
in the implementation of the concrete type.
impl<'a> Trait<'a> for Foo {
type Iter = std::slice::Iter<'a, &'a str>;
fn iter(&self) -> Self::Iter {
self.data
.iter()
.map(|item| item.as_str())
}
Well - this fails to compile as the iterator provided by the implementation is actually a different type:
expected struct `std::slice::Iter<'_, &str>`
found struct `std::iter::Map<std::slice::Iter<'_, String>, [closure@src/test.rs:60:12: 60:43]>
The question now would be - how to specify and restrict the iterator definition in the trait so it can kind of accept any kind of Iterator
that yields items with specific behavior like being able to be converted to &str
. So the implementation finally running on the items of the returned iterator can be properly used without the need to know the exact iterator type:
fn foo<'a, T: Trait<'a>>(value: T) {
for item in value.iter() {
dbg!(item); // here the item should be a &str or being able to be converted into &str with as_str()
}
}
Any hints are much appreciated.