Skip to content

Commit

Permalink
Update README to indicate how to replace with std::sync::OnceLock
Browse files Browse the repository at this point in the history
  • Loading branch information
frewsxcv committed Nov 25, 2023
1 parent 5735630 commit 41fa234
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ as well as anything that requires non-const function calls to be computed.
[![Documentation](https://docs.rs/lazy_static/badge.svg)](https://docs.rs/lazy_static)
[![License](https://img.shields.io/crates/l/lazy_static.svg)](https://github.com/rust-lang-nursery/lazy-static.rs#license)


## Minimum supported `rustc`

`1.40.0+`
Expand Down Expand Up @@ -61,6 +62,35 @@ 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 be also be written as:

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

static HASHMAP: OnceLock<HashMap<u32, &'static str>> = OnceLock::new();

fn hashmap() -> &'static HashMap<u32, &'static str> {
HASHMAP.get_or_init(|| {
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());

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

## License

Licensed under either of
Expand Down

0 comments on commit 41fa234

Please sign in to comment.