@@ -13,22 +13,54 @@ use crate::sync::Once;
13
13
///
14
14
/// # Examples
15
15
///
16
+ /// Using `OnceCell` to store a function’s previously computed value (a.k.a.
17
+ /// ‘lazy static’ or ‘memoizing’):
18
+ ///
19
+ /// ```
20
+ /// use std::collections::HashMap;
21
+ /// use std::sync::OnceLock;
22
+ ///
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
+ /// })
32
+ /// }
33
+ ///
34
+ /// // The `HashMap` is built, stored in the `OnceLock`, and returned.
35
+ /// let _ = hash_map();
36
+ ///
37
+ /// // The `HashMap` is retrieved from the `OnceLock` and returned.
38
+ /// let _ = hash_map();
39
+ /// ```
40
+ ///
41
+ /// Writing to a `OnceLock` from a separate thread:
42
+ ///
16
43
/// ```
17
44
/// use std::sync::OnceLock;
18
45
///
19
- /// static CELL: OnceLock<String> = OnceLock::new();
46
+ /// static CELL: OnceLock<usize> = OnceLock::new();
47
+ ///
48
+ /// // `OnceLock` has not been written to yet.
20
49
/// assert!(CELL.get().is_none());
21
50
///
51
+ /// // Spawn a thread and write to `OnceLock`.
22
52
/// std::thread::spawn(|| {
23
- /// let value: &String = CELL.get_or_init(|| {
24
- /// "Hello, World!".to_string()
25
- /// });
26
- /// assert_eq!(value, "Hello, World!");
27
- /// }).join() .unwrap();
53
+ /// let value = CELL.get_or_init(|| 12345);
54
+ /// assert_eq!(value, &12345);
55
+ /// })
56
+ /// .join()
57
+ /// .unwrap();
28
58
///
29
- /// let value: Option<&String> = CELL.get();
30
- /// assert!(value.is_some());
31
- /// assert_eq!(value.unwrap().as_str(), "Hello, World!");
59
+ /// // `OnceLock` now contains the value.
60
+ /// assert_eq!(
61
+ /// CELL.get(),
62
+ /// Some(&12345),
63
+ /// );
32
64
/// ```
33
65
#[ stable( feature = "once_cell" , since = "1.70.0" ) ]
34
66
pub struct OnceLock < T > {
0 commit comments