Some values cannot be created via const functions. I’m aware of the following options for setting up immutable global static values:
lazy_static! {
static ref HM1: HashMap<String, String> = HashMap::new();
}
use once_cell::sync::Lazy;
static HM2: Lazy<HashMap<String, String>> =
Lazy::new(|| HashMap::new());
use std::sync::LazyLock;
static HM3: LazyLock<HashMap<String, String>> =
LazyLock::new(|| HashMap::new());
Is the following correct? Are there more options?
- A downside of
lazy_static
is that it’s a macro and that there may be race conditions if multiple threads access the values. On the upside, it does have convenient syntax. - Once
std::sync::LazyLock
becomes stable, it is the best solution(?)- I’m confused by it having the name of a crate that doesn’t seem to exist anymore: I thought it was derived from
once_cell::sync::Lazy
.
- I’m confused by it having the name of a crate that doesn’t seem to exist anymore: I thought it was derived from
If the above is true, I’d use once_cell::sync::Lazy
to prepare for std::sync::LazyLock
becoming stable.