Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use LazyLock instead of OnceLock in the std example #225

Merged
merged 1 commit into from
Dec 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading