简体   繁体   English

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

[英]Declaring Lifetime of Closure in Struct

From the various sources I can find, giving a lifetime to a property in a struct would be done like so: 从我可以找到的各种来源中,给struct的属性赋予生命周期就像这样:

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

Use of the &'self lifetime is now deprecated. 现在不推荐使用&'self生命周期。 When declaring a property to be a closure type, the compiler tells me it needs a lifetime specifier, but I cannot find an example anywhere that has a closure as a property of a struct. 当声明一个属性是一个闭包类型时,编译器告诉我它需要一个生命周期说明符,但我找不到一个有闭包作为结构属性的示例。

This is what I am currently trying: 这就是我目前正在尝试的:

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

But I get the following error: error: missing lifetime specifier [E0106] 但是我收到以下错误: error: missing lifetime specifier [E0106]

What is the proper syntax for declaring a lifetime of a closure in a struct , or any type for that matter? struct声明closure的生命周期的正确语法是什么,或者是什么类型的?

Updated to Rust 1.4. 更新为Rust 1.4。

Closures are now based on one of three traits, Fn , FnOnce , and FnMut . 闭包现在基于三个特征之一, FnFnOnceFnMut

The type of a closure cannot be defined precisely, we can only bound a generic type to one of the closure traits. 闭包的类型不能精确定义,我们只能将泛型类型绑定到闭包特征之一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM