Skip to content

Commit

Permalink
Merge pull request #225 from josephcsible/patch-1
Browse files Browse the repository at this point in the history
Use LazyLock instead of OnceLock in the std example
  • Loading branch information
KodrAus authored Dec 22, 2024
2 parents cc81425 + e5730c6 commit f9ee0cc
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,29 +63,26 @@ fn main() {

# Standard library

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 also be written as:
It is now possible to easily replicate this crate's functionality in Rust's standard library with [`std::sync::LazyLock`](https://doc.rust-lang.org/std/sync/struct.LazyLock.html). The example above could also be written as:

```rust
use std::collections::HashMap;
use std::sync::OnceLock;
use std::sync::LazyLock;

fn hashmap() -> &'static HashMap<u32, &'static str> {
static HASHMAP: OnceLock<HashMap<u32, &str>> = OnceLock::new();
HASHMAP.get_or_init(|| {
let mut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
m
})
}
static HASHMAP: LazyLock<HashMap<u32, &str>> = LazyLock::new(|| {
let mut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
m
});

fn main() {
// First access to `HASHMAP` initializes it
println!("The entry for `0` is \"{}\".", hashmap().get(&0).unwrap());
println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());

// Any further access to `HASHMAP` just returns the computed value
println!("The entry for `1` is \"{}\".", hashmap().get(&1).unwrap());
println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap());
}
```

Expand Down

0 comments on commit f9ee0cc

Please sign in to comment.