@@ -13,22 +13,54 @@ use crate::sync::Once;
1313/// 
1414/// # Examples 
1515/// 
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+ /// 
1643/// ``` 
1744/// use std::sync::OnceLock; 
1845/// 
19- /// static CELL: OnceLock<String> = OnceLock::new(); 
46+ /// static CELL: OnceLock<usize> = OnceLock::new(); 
47+ /// 
48+ /// // `OnceLock` has not been written to yet. 
2049/// assert!(CELL.get().is_none()); 
2150/// 
51+ /// // Spawn a thread and write to `OnceLock`. 
2252/// 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(); 
2858/// 
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+ /// ); 
3264/// ``` 
3365#[ stable( feature = "once_cell" ,  since = "1.70.0" ) ]  
3466pub  struct  OnceLock < T >  { 
0 commit comments