Provide lazy_static static ref with lifetimes

Viewed 219

Is it possible to provide a lazy static with lifetime args?

use lazy_static::lazy_static; //lazy_static = "1.4.0"

enum MyEnum<'a>{
    Name(&'a str)
}

lazy_static! {
    static ref STATIC_ENUM: Mutex<MyEnum<'a>> = Mutex::new(MyEnum::Name("some name"));
}


gives:

error[E0261]: use of undeclared lifetime name `'a`
    static ref STATIC_ENUM: Mutex<MyEnum<'a>> = Mutex::new(MyEnum::Name("some name"));
                                           ^^ undeclared lifetime
1 Answers

Yes, but the only lifetime you can use for the value of any static variable (lazy or not) is the 'static lifetime.

lazy_static! {
    static ref STATIC_ENUM: Mutex<MyEnum<'static>> = Mutex::new(MyEnum::Name("some name"));
}

This may present a problem if you want to put in an &str that is not a literal (or deliberately leaked). If you need to do that, probably you should not be using a reference at all, but an owned String, at which point your enum no longer needs a lifetime parameter:

enum MyEnum {
    Name(String),
}

Also, consider using once_cell::sync::Lazy instead of lazy_static::lazy_static. It won't give you any particular advantage here, but it doesn't use a macro so it doesn't hide things like the actual type of the static.

Related