Skip to content

Commit

Permalink
Merge pull request #216 from frewsxcv/patch-1
Browse files Browse the repository at this point in the history
Update README to indicate how to replace with `std::sync::OnceLock`
  • Loading branch information
KodrAus committed Nov 26, 2023
2 parents 5735630 + a203105 commit 6ace970
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,34 @@ 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;

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
})
}

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 6ace970

Please sign in to comment.