相关疑难解决方法(0)

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

我想在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"),
    // …
Run Code Online (Sandbox Code Playgroud)

closures lifetime rust

17
推荐指数
3
解决办法
4236
查看次数

为什么在包含闭包的选项中“一种类型比另一种更通用”?

我写了一些编译好的代码,然后我变成TOption<T>,现在我收到了这个错误:

error[E0308]: mismatched type...one type is more general than the other
Run Code Online (Sandbox Code Playgroud)

在构建最小案例时,我注意到如果我更改data: &strdata: String代码再次编译正常。

游乐场链接

pub trait Subscriber {
    fn recv(&mut self, data: &str);
}

pub struct Task<T>(pub Option<T>)
where
    T: Fn(&str);

impl<T> Subscriber for Task<T>
where
    T: Fn(&str),
{
    fn recv(&mut self, data: &str) {
        self.0.take().unwrap()(data)
    }
}

fn main() {
    Task(Some(|_| ()));
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我了解这里发生了什么吗?

rust

14
推荐指数
1
解决办法
1915
查看次数

类型不匹配解决了通过引用获取参数的闭包

我在尝试编译下面的 Rust 代码时遇到了一对奇怪的错误。在寻找具有类似问题的其他人时,我遇到了另一个问题,该问题具有相同的(看似相反的)错误组合,但无法将解决方案从那里推广到我的问题。

基本上,我似乎忽略了 Rust 所有权系统的一个微妙之处。尝试在这里编译(非常精简的)代码:

struct Point {
    x: f32,
    y: f32,
}

fn fold<S, T, F>(item: &[S], accum: T, f: F) -> T
where
    F: Fn(T, &S) -> T,
{
    f(accum, &item[0])
}

fn test<'a>(points: &'a [Point]) -> (&'a Point, f32) {
    let md = |(q, max_d): (&Point, f32), p: &'a Point| -> (&Point, f32) {
        let d = p.x + p.y; // Standing in for a function call
        if d > max_d {
            (p, d) …
Run Code Online (Sandbox Code Playgroud)

lifetime ownership rust

5
推荐指数
1
解决办法
2446
查看次数

标签 统计

rust ×3

lifetime ×2

closures ×1

ownership ×1