如何为闭包参数声明生命周期?

问题描述 投票:15回答:3

我想在Rust中为一个闭包声明一个生命周期,但我找不到添加生命周期声明的方法。

use std::str::SplitWhitespace;

pub struct ParserError {
    pub message: String,
}

fn missing_token(line_no: usize) -> ParserError {
    ParserError {
        message: format!("Missing token on line {}", line_no),
    }
}

fn process_string(line: &str, line_number: usize) -> Result<(), ParserError> {
    let mut tokens = line.split_whitespace();

    match try!(tokens.next().ok_or(missing_token(line_number))) {
        "hi" => println!("hi"),
        _ => println!("Something else"),
    }

    // The following code gives "cannot infer appropriate lifetime.....
    // let nt = |t: &mut SplitWhitespace| t.next().ok_or(missing_token(line_number));
    // match try!(nt(&mut tokens)) {
    //     "there" => println!("there"),
    //     _ => println!("_"),
    // }

    // Where should I declare the lifetime 'a?
    // let nt = |t: &'a mut SplitWhitespace| t.next().ok_or(missing_token(line_number));
    // match try!(nt(&mut tokens)) {
    //     "there" => println!("there"),
    //     _ => println!("_"),
    // }

    return Ok(());
}

fn main() {
    process_string("Hi there", 5).ok().expect("Error!!!");
    process_string("", 5).ok().expect("Error!!! 2");
}

Complete sample code on the playground

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src/main.rs:22:42
   |
22 |     let nt = |t: &mut SplitWhitespace| t.next().ok_or(missing_token(line_number));
   |                                          ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 22:14...
  --> src/main.rs:22:14
   |
22 |     let nt = |t: &mut SplitWhitespace| t.next().ok_or(missing_token(line_number));
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator
note: but, the lifetime must be valid for the call at 23:16...
  --> src/main.rs:23:16
   |
23 |     match try!(nt(&mut tokens)) {
   |                ^^^^^^^^^^^^^^^
note: ...so type `std::result::Result<&str, ParserError>` of expression is valid during the expression
  --> src/main.rs:23:16
   |
23 |     match try!(nt(&mut tokens)) {
   |                ^^^^^^^^^^^^^^^

如何为此闭包声明生命周期'a

closures rust lifetime
3个回答
10
投票

&mut SplitWhitespace实际上是&'b mut SplitWhitespace<'a>。这里的相关生命周期是'a,因为它指定了next返回的字符串切片有多长。由于您在split_whitespace参数上应用了line函数,因此需要将'a设置为与line参数相同的生命周期。

因此,作为第一步,您将为line添加生命周期:

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

然后将生命周期添加到闭包中的类型:

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

请注意,虽然这可以回答您的问题,但问题的正确解决方案是@A.B.'s solution


8
投票

我不知道如何回答你的问题,但有两种方法可以解决这个问题:

最简单的方法是让闭包直接引用迭代器。

{
    let mut nt = || tokens.next().ok_or(missing_token(line_number));
    // call the closure as many times as you need to
}
    // At this point `tokens` will be usable again.

如果你事后不需要用tokens做其他事情,那就做:

let mut nt = || tokens.next().ok_or(missing_token(line_number)); 

另一个解决方案是编写一个函数来模拟闭包正在做什么并调用它。


3
投票

与最初的pointed out by DK.一样,您可以使用函数将额外的约束应用于闭包的参数并返回值:

fn constrain<F>(f: F) -> F
where
    F: for<'a> Fn(&'a mut SplitWhitespace) -> Result<&'a str, ParserError>,
{
    f
}

这为你提供了where条款的全部能力;在这种情况下,您可以使用排名较高的特征边界(for <...>)来表示闭包必须返回与参数相同生命周期的引用。

let nt = constrain(|t| t.next().ok_or(missing_token(line_number)));

最终,这是由于limitations in Rust's type inference引起的。具体来说,如果闭包被立即传递给使用它的函数,编译器可以推断出参数和返回类型是什么。不幸的是,当它在使用之前存储在变量中时,编译器不会执行相同级别的推断。

这种解决方法有效,因为它会立即将闭包传递给函数,从而确定类型和生命周期引用。

© www.soinside.com 2019 - 2024. All rights reserved.