Skip to content

Commit 41fa234

Browse files
authored
Update README to indicate how to replace with std::sync::OnceLock
1 parent 5735630 commit 41fa234

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ as well as anything that requires non-const function calls to be computed.
1313
[![Documentation](https://docs.rs/lazy_static/badge.svg)](https://docs.rs/lazy_static)
1414
[![License](https://img.shields.io/crates/l/lazy_static.svg)](https://github.com/rust-lang-nursery/lazy-static.rs#license)
1515

16+
1617
## Minimum supported `rustc`
1718

1819
`1.40.0+`
@@ -61,6 +62,35 @@ fn main() {
6162
}
6263
```
6364

65+
# Standard library
66+
67+
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:
68+
69+
```rust
70+
use std::collections::HashMap;
71+
use std::sync::OnceLock;
72+
73+
static HASHMAP: OnceLock<HashMap<u32, &'static str>> = OnceLock::new();
74+
75+
fn hashmap() -> &'static HashMap<u32, &'static str> {
76+
HASHMAP.get_or_init(|| {
77+
let mut m = HashMap::new();
78+
m.insert(0, "foo");
79+
m.insert(1, "bar");
80+
m.insert(2, "baz");
81+
m
82+
})
83+
}
84+
85+
fn main() {
86+
// First access to `HASHMAP` initializes it
87+
println!("The entry for `0` is \"{}\".", hashmap().get(&0).unwrap());
88+
89+
// Any further access to `HASHMAP` just returns the computed value
90+
println!("The entry for `1` is \"{}\".", hashmap().get(&1).unwrap());
91+
}
92+
```
93+
6494
## License
6595

6696
Licensed under either of

0 commit comments

Comments
 (0)