diff options
| author | Ian Rees <code@ianrees.nz> | 2023-12-04 15:18:58 +1300 |
|---|---|---|
| committer | Ian Rees <code@ianrees.nz> | 2023-12-08 09:49:54 +1300 |
| commit | 88fccc465f157ecc84ec8df9af724fd7d155d534 (patch) | |
| tree | cc4403decd28443e2aacc82a1fd4ceca648105b8 | |
| parent | 0e7f91b75e7484a713e2f644212cfc1aa7478a28 (diff) | |
| download | rust-88fccc465f157ecc84ec8df9af724fd7d155d534.tar.gz rust-88fccc465f157ecc84ec8df9af724fd7d155d534.zip | |
OnceLock: Rework example, statics aren't dropped
| -rw-r--r-- | library/std/src/sync/once_lock.rs | 39 |
1 files changed, 25 insertions, 14 deletions
diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index 52a43913243..b8873a3b59a 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -17,25 +17,36 @@ use crate::sync::Once; /// ‘lazy static’ or ‘memoizing’): /// /// ``` -/// use std::collections::HashMap; /// use std::sync::OnceLock; /// -/// fn hash_map() -> &'static HashMap<u32, char> { -/// static HASHMAP: OnceLock<HashMap<u32, char>> = OnceLock::new(); -/// HASHMAP.get_or_init(|| { -/// let mut m = HashMap::new(); -/// m.insert(0, 'a'); -/// m.insert(1, 'b'); -/// m.insert(2, 'c'); -/// m -/// }) +/// struct DeepThought { +/// answer: String, /// } /// -/// // The `HashMap` is built, stored in the `OnceLock`, and returned. -/// let _ = hash_map(); +/// impl DeepThought { +/// # fn great_question() -> String { +/// # "42".to_string() +/// # } +/// # +/// fn new() -> Self { +/// Self { +/// // M3 Ultra takes about 16 million years in --release config +/// answer: Self::great_question(), +/// } +/// } +/// } +/// +/// fn computation() -> &'static DeepThought { +/// // n.b. static items do not call [`Drop`] on program termination, so if +/// // [`DeepThought`] impls Drop, that will not be used for this instance. +/// static COMPUTATION: OnceLock<DeepThought> = OnceLock::new(); +/// COMPUTATION.get_or_init(|| DeepThought::new()) +/// } /// -/// // The `HashMap` is retrieved from the `OnceLock` and returned. -/// let _ = hash_map(); +/// // The `DeepThought` is built, stored in the `OnceLock`, and returned. +/// let _ = computation().answer; +/// // The `DeepThought` is retrieved from the `OnceLock` and returned. +/// let _ = computation().answer; /// ``` /// /// Writing to a `OnceLock` from a separate thread: |
