我想为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美元?

推荐答案

&mut SplitWhitespace实际上是&'b mut SplitWhitespace<'a>.这里的相关生存期是'a,因为它指定next返回live的字符串片段的长度.由于在line参数上应用了split_whitespace函数,因此需要将'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.

Rust相关问答推荐

如何在Rust中表示仅具有特定大小的数组

编译项目期间使用Cargo生成时出现rustc错误

你是如何在铁 rust 一侧的金牛座获得应用程序版本的?

闭包不会发送,即使它只捕获发送变量

自定义结果枚举如何支持`?`/`FromResidual`?

S在Cargo.toml中添加工作空间开发依赖关系的正确方法是什么?

一种随机局部搜索算法的基准(分数)

Rust 的多态现象.AsRef与Derf

如果死 struct 实现了/派生了一些特征,为什么Rust会停止检测它们?

当发送方分配给静态时,Tokio MPSC关闭通道

为什么Option类型try块需要类型注释?

在使用粗粒度锁访问的数据 struct 中使用 RefCell 是否安全?

如何在 `connect_activate()` 之外创建一个 `glib::MainContext::channel()` 并将其传入?

Rust Option 的空显式泛型参数

Rust FFI 和 CUDA C 性能差异

将 &str 或 String 保存在变量中

需要一个有序向量来进行 struct 初始化

缺失serde的字段无法设置为默认值

Rust 中函数的类型同义词

您如何使用枚举反序列化字符串,其中任何其他值反序列化为新类型变体同时保留字符串?