1

This is a toy problem but should represent what I'm actually doing pretty closely. I'm making a function that returns a structure that holds a few lambda functions. These functions share a variable that was captured into them. I've attached this variable to the same structure that owns the lambdas, so everything should cleanly go out of scope at the same time:


struct Foo{
    fx: Box<dyn Fn()>,
    gx: Box<dyn Fn()>,
    st: String,
}

fn make_foo() -> Foo {
    let s = String::from("hello world");
    
    Foo {
        fx: Box::new(|| println!("{}", s)),
        gx: Box::new(|| println!("{}", s)),
        st: s,
    }
}


fn main() {

    let foo = make_foo();
    (foo.fx)();
    (foo.gx)();

}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f26344947f4dd8fef04dbe5034bafca4

Unfortunately, the compiler isn't smart enough to figure this out (or I have syntax errors), and I am not smart enough to understand what lifetime syntax to use use here. I'm pretty much a rust noob, so some of the complexities of the lifetime syntax escapes me. I would like both fx and gx to capture a reference to the string "hello world", and I would like all of those to be annotated with the same lifetime so that rust doesn't cry foul about the lambda's potentially outliving the captured value.

I'm aware that as a work around I could define s as an Arc or something similar but that is overkill for my case, so I'm avoiding it when possible.

Or, perhaps this just isn't the rust way of doing things. If so, I'm happy to hear alternatives.

Hounddog
  • 385
  • 1
  • 10
  • 2
    There is probably a better way to achieve what you're attempting to do, but it's hard to tell what your actual objective is from the example you give. – PitaJ Oct 18 '22 at 22:07

0 Answers0