Setting up global “constants”?

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.

If the above is true, I’d use once_cell::sync::Lazy to prepare for std::sync::LazyLock becoming stable.

LazyLock is the std equivalent of once_cell's Lazy. It looks like the "Lock" suffix was chosen for the version of OnceCell and related types that implement Sync.

1 Like

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.