Skip to content

Commit 82e806f

Browse files
authored
fix: make LazyLock example demonstrate realistic applicatino
1 parent ea7fb4a commit 82e806f

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

src/mem/global_static/lazy-constant.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -79,25 +79,28 @@ The [`LazyLock`] type is a thread-safe alternative to [`LazyCell`].
7979
use std::sync::LazyLock;
8080
use std::collections::HashMap;
8181
82-
static PRIVILEGES: LazyLock<HashMap<&'static str, Vec<&'static str>>> = LazyLock::new(|| {
83-
{
84-
let mut map = HashMap::new();
85-
map.insert("James", vec!["user", "admin"]);
86-
map.insert("Jim", vec!["user"]);
87-
map
82+
struct Config {
83+
api_key: String,
84+
timeout: u64,
85+
}
86+
87+
// Imagine loading this from a .env file or a vault
88+
static APP_CONFIG: LazyLock<Config> = LazyLock::new(|| {
89+
println!("Loading configuration...");
90+
Config {
91+
api_key: std::env::var("API_KEY").unwrap_or_else(|_| "default_key".to_string()),
92+
timeout: 30,
8893
}
8994
});
9095
91-
fn show_access(name: &str) {
92-
let access = PRIVILEGES.get(name);
93-
println!("{}: {:?}", name, access);
94-
}
95-
9696
fn main() {
97-
let access = PRIVILEGES.get("James");
98-
println!("James: {:?}", access);
97+
println!("App started.");
9998
100-
show_access("Jim");
99+
// The closure above isn't run until we access APP_CONFIG here.
100+
let timeout = APP_CONFIG.timeout;
101+
102+
println!("Timeout is: {}s", timeout);
103+
println!("API Key is hidden: {}", APP_CONFIG.api_key.len() > 0);
101104
}
102105
```
103106
[`LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html

0 commit comments

Comments
 (0)