问题 声明结构中闭包的生命周期


从我可以找到的各种来源,给一个属性的生命 struct 会这样做:

pub struct Event<'self> {
    name: String,
    execute: &'self |data: &str|
}

使用的 &'self 生命周期现已弃用。当声明一个属性是一个闭包类型时,编译器告诉我它需要一个生命周期说明符,但我找不到一个有闭包作为结构属性的示例。

这就是我目前正在尝试的:

pub struct Event<'a> {
    name: String,
    execute: &'a |data: &str|
}

但是我收到以下错误: error: missing lifetime specifier [E0106]

声明a的生命周期的正确语法是什么 closure 在一个 struct,或任何类型的事情?


2580
2017-08-07 13:49


起源



答案:


更新为Rust 1.4。

关闭现在基于三个特征之一, FnFnOnce,和 FnMut

闭包的类型不能精确定义,我们只能将泛型类型绑定到闭包特征之一。

pub struct Event<F: Fn(&str) -> bool> {
    name: String,
    execute: F
}

11
2017-08-07 13:58



不对称有些不和谐:/ - Matthieu M.
当我尝试时,我明白了 error: expected type, found `|` 。这样做的正确方法是什么? - Alex Knauth
@AlexKnauth我更新了帖子。 - A.B.
如果我已经尝试在两种类型上使结构泛型,我该怎么做呢?我希望根据这些类型定义闭包类型? - Alex Knauth


答案:


更新为Rust 1.4。

关闭现在基于三个特征之一, FnFnOnce,和 FnMut

闭包的类型不能精确定义,我们只能将泛型类型绑定到闭包特征之一。

pub struct Event<F: Fn(&str) -> bool> {
    name: String,
    execute: F
}

11
2017-08-07 13:58



不对称有些不和谐:/ - Matthieu M.
当我尝试时,我明白了 error: expected type, found `|` 。这样做的正确方法是什么? - Alex Knauth
@AlexKnauth我更新了帖子。 - A.B.
如果我已经尝试在两种类型上使结构泛型,我该怎么做呢?我希望根据这些类型定义闭包类型? - Alex Knauth