Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Lifetime of Closure in Struct

Tags:

rust

lifetime

From the various sources I can find, giving a lifetime to a property in a struct would be done like so:

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

Use of the &'self lifetime is now deprecated. 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]

What is the proper syntax for declaring a lifetime of a closure in a struct, or any type for that matter?

like image 597
nathansizemore Avatar asked Aug 07 '14 13:08

nathansizemore


1 Answers

Updated to Rust 1.4.

Closures are now based on one of three traits, Fn, FnOnce, and FnMut.

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
}
like image 110
A.B. Avatar answered Oct 29 '22 04:10

A.B.