Skip to content

Commit e7767d5

Browse files
committed
OnceLock: Rework example, statics aren't dropped
1 parent 1fdfe12 commit e7767d5

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

library/std/src/sync/once_lock.rs

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,28 @@ use crate::sync::Once;
1717
/// ‘lazy static’ or ‘memoizing’):
1818
///
1919
/// ```
20-
/// use std::collections::HashMap;
2120
/// use std::sync::OnceLock;
2221
///
23-
/// fn hash_map() -> &'static HashMap<u32, char> {
24-
/// static HASHMAP: OnceLock<HashMap<u32, char>> = OnceLock::new();
25-
/// HASHMAP.get_or_init(|| {
26-
/// let mut m = HashMap::new();
27-
/// m.insert(0, 'a');
28-
/// m.insert(1, 'b');
29-
/// m.insert(2, 'c');
30-
/// m
31-
/// })
22+
/// struct Computation {}
23+
///
24+
/// impl Computation {
25+
/// fn new() -> Self {
26+
/// // Do some slow/expensive computation here
27+
/// Self {}
28+
/// }
3229
/// }
3330
///
34-
/// // The `HashMap` is built, stored in the `OnceLock`, and returned.
35-
/// let _ = hash_map();
31+
/// fn computation() -> &'static Computation {
32+
/// // n.b. static items do not call [`Drop`] on program termination, so if
33+
/// // [`Computation`] impls Drop, that will not be used for this instance.
34+
/// static COMPUTATION: OnceLock<Computation> = OnceLock::new();
35+
/// COMPUTATION.get_or_init(|| Computation::new())
36+
/// }
3637
///
37-
/// // The `HashMap` is retrieved from the `OnceLock` and returned.
38-
/// let _ = hash_map();
38+
/// // The `Computation` is built, stored in the `OnceLock`, and returned.
39+
/// let _ = computation();
40+
/// // The `Computation` is retrieved from the `OnceLock` and returned.
41+
/// let _ = computation();
3942
/// ```
4043
///
4144
/// Writing to a `OnceLock` from a separate thread:

0 commit comments

Comments
 (0)