Skip to content

Commit 7706a93

Browse files
committed
fix: make LazyLock and LazyCell examples demonstrate realistic applications
1 parent ea7fb4a commit 7706a93

File tree

1 file changed

+47
-22
lines changed

1 file changed

+47
-22
lines changed

src/mem/global_static/lazy-constant.md

Lines changed: 47 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,37 @@ fn main() {
5959
```rust,edition2021
6060
use std::cell::LazyCell;
6161
62-
fn main() {
63-
let lazy: LazyCell<usize> = LazyCell::new(|| {
64-
println!("Evaluated Lazily");
65-
5
66-
});
67-
println!("Starting Program!");
68-
let lazy_constant = &*lazy;
69-
assert_eq!(*lazy_constant, 5);
62+
struct User {
63+
id: u32,
64+
username: String,
65+
// We defer the expensive permission calculation
66+
permissions: LazyCell<Vec<String>>,
7067
}
68+
69+
impl User {
70+
fn new(id: u32, username: String) -> Self {
71+
Self {
72+
id,
73+
username,
74+
permissions: LazyCell::new(|| {
75+
println!("--- Fetching permissions from database for ID {} ---", id);
76+
// Simulate a heavy operation
77+
vec!["read".to_string(), "write".to_string()]
78+
}),
79+
}
80+
}
81+
}
82+
83+
fn main() {
84+
let user = User::new(1, "ferris_rustacean".into());
85+
86+
println!("User {} loaded.", user.username);
87+
88+
// If we never access user.permissions, the closure is never run.
89+
90+
if true { // Imagine a conditional check here
91+
println!("Permissions: {:?}", *user.permissions);
92+
}
7193
```
7294

7395
[`LazyCell`]: https://doc.rust-lang.org/std/cell/struct.LazyCell.html
@@ -79,25 +101,28 @@ The [`LazyLock`] type is a thread-safe alternative to [`LazyCell`].
79101
use std::sync::LazyLock;
80102
use std::collections::HashMap;
81103
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
104+
struct Config {
105+
api_key: String,
106+
timeout: u64,
107+
}
108+
109+
// Imagine loading this from a .env file or a vault
110+
static APP_CONFIG: LazyLock<Config> = LazyLock::new(|| {
111+
println!("Loading configuration...");
112+
Config {
113+
api_key: std::env::var("API_KEY").unwrap_or_else(|_| "default_key".to_string()),
114+
timeout: 30,
88115
}
89116
});
90117
91-
fn show_access(name: &str) {
92-
let access = PRIVILEGES.get(name);
93-
println!("{}: {:?}", name, access);
94-
}
95-
96118
fn main() {
97-
let access = PRIVILEGES.get("James");
98-
println!("James: {:?}", access);
119+
println!("App started.");
99120
100-
show_access("Jim");
121+
// The closure above isn't run until we access APP_CONFIG here.
122+
let timeout = APP_CONFIG.timeout;
123+
124+
println!("Timeout is: {}s", timeout);
125+
println!("API Key is hidden: {}", APP_CONFIG.api_key.len() > 0);
101126
}
102127
```
103128
[`LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html

0 commit comments

Comments
 (0)