n0dwis
January 16, 2020, 1:37pm
1
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!
alice
January 16, 2020, 1:54pm
2
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
system
Closed
April 15, 2020, 2:20pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.