Correct lifetime for closure type to allow mutable reference to struct to exist in the closure

I'm in the process of writing a dynamic type system for a language I am helping develop (types being akin to structs). The language has a Globals struct which is instanced before execution of the bytecode. The globals instance includes a hashmap all of the language's types and therefore is guaranteed to outlive them (I believe so, anyway). No reference to a type (or multiple) would ever exist after globals had been dropped.

In essence, this code demonstrates the problem I am having:

fn construct_type(globals: &mut Globals) -> Arc<dyn Fn() -> String + 'static> {
    Arc::new(|| { globals.string.clone() })

pub struct Globals {
    pub string: String,

fn main<'a>() {
    let mut globals = Globals { string: String::from("something") };
    let t = construct_type(&mut globals);
    // insert `t` into `globals`

and the error being:

error: lifetime may not live long enough
....returning this value requires that `'1` must outlive `'static`

where '1 is indicating &mut globals and 'static being the closure. Of course, the simple solution here is to change 'static to '_ as the error message states, but in the code for types, iunfortunately it isn't that simple.

In the code, if I don't mark the closure with 'static I get the error that

the parameter type `F` may not live long enough

Even trying to give it named lifetimes, it still errors. Althought, placing 'static on it does get rid of the errors, it then has the same issue above where it doesn't like that globals is not 'static (the error is instead borrowed data escapes outside of function but with the same core lifetime issue). It seems like my only solution so far is to make globals a mutable static, but that feels hacky, and I really wonder if anyone knows of any way to use lifetimes to make this work. The playground with the type code is linked below.

(Full playground example)

This isn't possible as-is. You put the function in an Arc which can arbitrarily extend its lifespan. Hence, it can't reference locals. You could try putting Globals behind an Arc as well.

Unfortunate. Thanks for the recomendation of Arc though, I didn't think about that and it does fix the issue, so I'll have to work that in somehow.

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.