Skip to content

Commit

Permalink
OnceLock: Rework example, statics aren't dropped
Browse files Browse the repository at this point in the history
  • Loading branch information
ianrrees committed Dec 6, 2023
1 parent 1fdfe12 commit e7767d5
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions library/std/src/sync/once_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,28 @@ 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 Computation {}
///
/// impl Computation {
/// fn new() -> Self {
/// // Do some slow/expensive computation here
/// Self {}
/// }
/// }
///
/// // The `HashMap` is built, stored in the `OnceLock`, and returned.
/// let _ = hash_map();
/// fn computation() -> &'static Computation {
/// // n.b. static items do not call [`Drop`] on program termination, so if
/// // [`Computation`] impls Drop, that will not be used for this instance.
/// static COMPUTATION: OnceLock<Computation> = OnceLock::new();
/// COMPUTATION.get_or_init(|| Computation::new())
/// }
///
/// // The `HashMap` is retrieved from the `OnceLock` and returned.
/// let _ = hash_map();
/// // The `Computation` is built, stored in the `OnceLock`, and returned.
/// let _ = computation();
/// // The `Computation` is retrieved from the `OnceLock` and returned.
/// let _ = computation();
/// ```
///
/// Writing to a `OnceLock` from a separate thread:
Expand Down

0 comments on commit e7767d5

Please sign in to comment.