Skip to content

Commit 6ace970

Browse files
authored
Merge pull request #216 from frewsxcv/patch-1
Update README to indicate how to replace with `std::sync::OnceLock`
2 parents 5735630 + a203105 commit 6ace970

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: README.md

+28
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,34 @@ fn main() {
6161
}
6262
```
6363

64+
# Standard library
65+
66+
It is now possible to easily replicate this crate's functionality in Rust's standard library with [`std::sync::OnceLock`](https://doc.rust-lang.org/std/sync/struct.OnceLock.html). The example above could be also be written as:
67+
68+
```rust
69+
use std::collections::HashMap;
70+
use std::sync::OnceLock;
71+
72+
fn hashmap() -> &'static HashMap<u32, &'static str> {
73+
static HASHMAP: OnceLock<HashMap<u32, &str>> = OnceLock::new();
74+
HASHMAP.get_or_init(|| {
75+
let mut m = HashMap::new();
76+
m.insert(0, "foo");
77+
m.insert(1, "bar");
78+
m.insert(2, "baz");
79+
m
80+
})
81+
}
82+
83+
fn main() {
84+
// First access to `HASHMAP` initializes it
85+
println!("The entry for `0` is \"{}\".", hashmap().get(&0).unwrap());
86+
87+
// Any further access to `HASHMAP` just returns the computed value
88+
println!("The entry for `1` is \"{}\".", hashmap().get(&1).unwrap());
89+
}
90+
```
91+
6492
## License
6593

6694
Licensed under either of

0 commit comments

Comments
 (0)