Transition from a structure with a lifespan to a trait

I am trying to do a dash to represent something as an iterator over lines. If I use struct std :: slice :: Iter in the result of get_iterator, everything is fine.

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 the Iterator <& String> character

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 lifetime:

<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 do I define a trait and make an implementation to make it work?

By the way, why did the compiler call this lifetime 'a? It is not called anywhere, and usually rust corresponds to "anonymous life". Is this a bug that should be reported?

+3


source to share


1 answer


We want to declare a new lifetime in our StringList reference and make sure our returned trait we put in the Iterator is bound by that lifetime.

pub trait Value {
    fn get_iterator<'a>(&'a self) -> Box<Iterator<Item=&String> + 'a>;
}

struct StringList {
    strings: Vec<String>
}

impl Value for StringList {
    fn get_iterator<'a>(&'a self) -> Box<Iterator<Item=&String> + 'a> {
        Box::new(self.strings.iter())
    }
}

fn main() {
}

      



Edit: To answer your question about the lifetime of a, it is defined, but the docs don't show it. Click on the Iter return object in the Vec documentation, and you will see that "a is declared on this object. The implementation for Vec would have to inject the lifetime of 'a into the Vec reference received when iter () was called.

+2


source







All Articles