#Problem with ? operator and lifetimes

4 messages · Page 1 of 1 (latest)

knotty pumice
#

Hi, i am trying parse text with crate nom (and anyhow for errors), and i have method check and function parse, method has test_str parametrs and execute function with test_str as parameter, function parse return IResult<&str, Vec<(&str, Vec<&str>)>>, method take &str and Vec<(...)> as variable from returned IResult, so, if i use ? operator on executed function i have this error:

error[E0521]: borrowed data escapes outside of associated function
  --> src/decoder.rs:99:24
   |
98 |     fn check(&self, test_str: &str) -> Result<()> {
   |                       ----  - let's call the lifetime of this reference `'1`
   |                       |
   |                       `test_str` is a reference that is only valid in the associated function body
99 |         let (s, vec) = Decoder::parse(test_str)?;
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^
   |                        |
   |                        `test_str` escapes the associated function body here
   |                        argument requires that `'1` must outlive `'static`

but if I replace ? operator with .unwrap(), program is compiling successful.

Does anyone have any tips to help me with this problem?

My code:
check method, compile error:

fn check(&self, test_str: &str) -> Result<()> {
  let (s, vec) = Decoder::parse(test_str)?;
  println!("{:#?}", vec);
  Ok(())
}

check method, compile successful:

fn check(&self, test_str: &str) -> Result<()> {
  let (s, vec) = Decoder::parse(test_str).unwrap();
  println!("{:#?}", vec);
  Ok(())
}

parse function:

fn parse(data: &str) -> IResult<&str, Vec<(&str, Vec<&str>)>> {
  let (data, _) = tag("xyz ")(data)?;
  separated_list1(
    tag(", "),
    separated_pair(
      take_while1(|c: char| c.is_alphabetic() || c == '_'),
      tag(": "),
      separated_list1(
        tag(" "),
        take_while1(|c: char| c.is_alphabetic() || c == '_'),
      ),
    ),
  )(data)
}
vestal wren
#

Looking at this type: https://docs.rs/nom/latest/nom/type.IResult.html
The input type parameter I is also present as a type parameter in the error variant. I can almost guarantee you that this causes the issue, because by using ? you are trying to return an Err variant which contains the input type, in this case &str

#

Try this:

fn check<'a>(&self, test_str: &'a str) -> Result<(), nom::Err<nom::Error<&'a str>>> {}
#

(stdlib Result, not to be confused with whatever your type synonym is)