简体   繁体   中英

Provide lazy_static static ref with lifetimes

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

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 usingonce_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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM