I'm trying to make a trait to present something as iterator over &Strings. If I use struct std::slice::Iter in get_iterator result everyting is ok.
pub trait Value {
fn get_iterator(&self) -> Box<std::slice::Iter<String>>;
}
struct StringList {
strings: Vec<String>
}
impl Value for StringList {
fn get_iterator(&self) -> Box<std::slice::Iter<String>> {
Box::new(self.strings.iter())
}
}
fn main() {
}
But when I switch to trait Iterator<&String>
pub trait Value {
fn get_iterator(&self) -> Box<Iterator<Item=&String>>;
}
struct StringList {
strings: Vec<String>
}
impl Value for StringList {
fn get_iterator(&self) -> Box<Iterator<Item=&String>> {
Box::new(self.strings.iter())
}
}
fn main() {
}
rust complains about lifetimes:
<anon>:11:31: 11:37 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
<anon>:11 Box::new(self.strings.iter())
How should I define trait and make implementation to make it work?
By the way, why does compiler call this lifetime 'a? It is not named anywhere and usually rust complies about "anonymous lifetime". Is it a bug that should be reported?
fn get_first_item(x: &Vec<String>) -> Box<&str> { Box::new(&x[0]) }
works just fine. – Slava Baginov