How to declare a lifetime for a closure argument?

后端 未结 3 755
無奈伤痛
無奈伤痛 2020-11-30 11:10

I would like to declare a lifetime for a closure in Rust, but I can\'t find a way to add a lifetime declaration.

use std::str::SplitWhitespace;

pub struct P         


        
3条回答
  •  天涯浪人
    2020-11-30 11:37

    The &mut SplitWhitespace is actually a &'b mut SplitWhitespace<'a>. The relevant lifetime here is the 'a, as it specifies how long the string slices that next returns live. Since you applied the split_whitespace function on your line argument, you need to set 'a to the same lifetime that the line argument has.

    So as a first step you add a lifetime to line:

    fn process_string<'a>(line: &'a str, line_number: usize) -> Result<(), ParserError> {
    

    and then you add the lifetime to the type in your closure:

    let nt = |t: &mut SplitWhitespace<'a>| t.next().ok_or(missing_token(line_number));
    

    Note that while this answers your question, the correct solution to your Problem is @A.B.'s solution.

提交回复
热议问题