The lifetime of a function

The following code can't compile(playground):

struct StructFunc {
    f: fn(usize, usize) -> bool,
}

impl StructFunc {
    fn gen_closure<'a>(&self, data: &'a Vec<usize>) -> Box<dyn Fn(usize) -> bool + 'a> {
        Box::new(
            move |i: usize| (self.f)(i, data[i])
        )
    }
}

This is the error:

error: lifetime may not live long enough
  --> src\plot.rs:51:9
   |
50 |       fn gen_closure<'a>(&self, data: &'a Vec<usize>) -> Box<dyn Fn(usize) -> bool + 'a> {
   |                      --  - let's call the lifetime of this reference `'1`
   |                      |
   |                      lifetime `'a` defined here
51 | /         Box::new(
52 | |             move |i: usize| (self.f)(i, data[i])
53 | |         )
   | |_________^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

I trying to let it work like:

fn greater(x: usize, y: usize) -> bool {
    x > y
}

let struct_fun = StructFunc(greater);

Your closure is capturing self, but self doesn't have a lifetime bound involving 'a.

changing it to

fn gen_closure<'a>(&'a self, data: &'a Vec<usize>) -> Box<dyn Fn(usize) -> bool + 'a>

makes it compile. It may not actually be what you want though.

You could also avoid capturing self

fn gen_closure<'a>(&self, data: &'a Vec<usize>) -> Box<dyn Fn(usize) -> bool + 'a> {
    let f = self.f;
    Box::new(move |i: usize| (f)(i, data[i]))
}
6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.