Is it possible that Closure / Function is 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 am I getting this error? I also want Foo to work with normal functions and closures.

I know there has been a closure reform in the past, so what would be the correct signature for f

Foo to work with closures and functions?

+3


source to share


1 answer


If you put a closure inside a struct, you need to explicitly specify 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 this, you can read this blog post that covers this case. Here's the relevant part from a blog post:

Two cases where constraints will be specified are: (1) placing closures in a struct where all life names must be explicitly named and (2) specifying concurrent data APIs. In the first case, a struct definition containing a closure, you would expect to write something like the following ...

+3


source







All Articles