Maik Klein
Maik Klein

Reputation: 16148

Is it possible to have a Closure/Function as a member of a struct?

struct Foo<A,B>{
    f: |A| -> B // err: Missing life time specifier
}
impl<A,B> Foo<A,B>{
    fn new(f: |A| -> B) -> Foo<A,B>{
        Foo {f:f}
    }
}

Why do I get this error? I also want Foo to work with normal functions and closures.

I know that there was a closure reform in the past, so what would be the correct signature for f so that Foo works with closures and functions?

Upvotes: 3

Views: 484

Answers (1)

lucidd
lucidd

Reputation: 587

If you place a closure inside of a struct you need to explicitly name the lifetime.

struct Foo<'a,A,B>{
    f: |A|:'a -> B
}

impl<'a,A,B> Foo<'a,A,B>{
    fn new(f: |A| -> B) -> Foo<A,B>{
        Foo {f:f}
    }
}

For more information on that you can read this blog post which coveres this case. Here is the relevant part from the blog post:

The two cases where bounds would be specified are (1) placing closures into a struct, where all lifetimes must be explicitly named and (2) specifying data-parallel APIs. In the first case, a struct definition that contains a closure, you would expect to write something like the following ...

Upvotes: 3

Related Questions