I'm using cssparser
crate to parse some CSS code. I would like to create a closure that is able to parse a type
function. As a first step, I create a very simple code that way:
use cssparser::{Parser, ParserInput};
fn main() {
let input_string = "type(\"image/png\")";
let mut parser_input = ParserInput::new(input_string);
let mut parser = Parser::new(&mut parser_input);
let parse_type = |p: &mut Parser| {
p.expect_function_matching("type")?;
Ok("OK")
};
let res = parse_type(&mut parser);
}
I got the following error:
error[E0282]: type annotations needed for the closure `fn(&mut Parser<'_, '_>) -> std::result::Result<&str, _>`
--> src/main.rs:9:43
|
9 | p.expect_function_matching("type")?;
| ^ cannot infer type of error for `?` operator
|
= note: `?` implicitly converts the error value into a type implementing `From<BasicParseError<'_>>`
As read in this answer, I added the return type of my closure:
let parse_type = |p: &mut Parser| -> Result<&str, cssparser::BasicParseError> {
p.expect_function_matching("type")?;
Ok("OK")
};
I still have an error I don't understand:
error: lifetime may not live long enough
--> src/main.rs:9:9
|
8 | let parse_type = |p: &mut Parser| -> Result<&str, cssparser::BasicParseError> {
| - ---------------------------------------- return type of closure is std::result::Result<&str, BasicParseError<'2>>
| |
| has type `&mut Parser<'1, '_>`
9 | p.expect_function_matching("type")?;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
Apparently '1
is release before '2
. How can it be the case as the parameter of my closure is a reference? It should still be alive after the call to my closure, right?
I tried to explicitly annotate the lifetime of my objects but I wasn't able to find the correct way to do it; I always have an "undeclared lifetime" error. For instance:
let parse_type = |p: &mut Parser<'i, '_>| -> Result<&str, cssparser::BasicParseError<'i>> {
p.expect_function_matching("type")?;
Ok("OK")
};