nathansizemore
nathansizemore

Reputation: 3196

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:

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?

Upvotes: 11

Views: 2169

Answers (1)

A.B.
A.B.

Reputation: 16660

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
}

Upvotes: 11

Related Questions