"impl T" parameter and lifetime. Compiller error

Hi!
I got compiler error "the parameter type impl Parser may not live long enough" for this code

struct BoxedParser {
    parser: Box<dyn Parser>,
}

impl BoxedParser {
    fn new(p: impl Parser) -> Self {
        Self {
            parser: Box::new(p),
        }
    }
}

impl Parser for BoxedParser {
    fn parse<'a>(&self, in_string: &'a str) -> (Result<String, ()>, &'a str) {
        self.parser.parse(in_string)
    }
}

Why?? BoxedParser own a parser not borrow it. So lifetime should doesn't be matter!

What if the parser you're given is a struct with a field that's a borrow of something? You can tell the compiler that you only allow parsers that contain no borrows like this:

fn new(p: impl Parser + 'static) -> Self {

playground

1 Like

The compiler suggests the same thing as @alice below your error message, too:

help: consider adding an explicit lifetime bound  `'static` to `impl Parser`...
   |
10 |     fn new(p: impl Parser + 'static) -> Self {
   |        

Rust's error output is generally very helpful :slight_smile:

Thanks for all!