Closure returning borrowed value

fn stateful<ProduceOutputClj>(clj: ProduceOutputClj)
        ProduceOutputClj: FnMut(Box<dyn FnMut() -> Option<&usize>>)
    let next_update =  {
        let mut x = 1_usize;
        move || {
            if x < 5 { x += 1; Some(&x) }
            else { None }

fn main() {
    stateful(|next_update| { 
        while let Some(x) = next_update() {
            println!("next update is {:?}", x);



   Compiling playground v0.0.1 (/playground)
error[E0106]: missing lifetime specifier
 --> src/
4 |         ProduceOutputClj: FnMut(Box<dyn FnMut() -> Option<&usize>>)
  |                                                           ^ help: consider giving it a 'static lifetime: `&'static`
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

error: aborting due to previous error

For more information about this error, try `rustc --explain E0106`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

I'm having some trouble getting this code to compile due to lifetime issues.

What I would like to do is to provide the caller of the stateful function with a closure (next_update) that, when invoked multiple times, returns references to some data owned by the stateful function (x: usize in this example).

I tried to use explicit lifetimes but none of the my attemps worked out.

Thanks in advance.

You can't return references into the closure itself due to the signature of call_mut, which doesn't allow the Self::Output type to depend on the lifetime on the &mut self.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.