22#![ allow( unused_assignments) ]
33
44use std:: sync:: Once ;
5-
5+ use std:: sync:: OnceLock ;
6+ use std:: cell:: OnceCell ;
7+ use std:: thread:: sleep;
8+ use std:: time:: Duration ;
69
710pub fn once_example ( ) {
811 let once = Once :: new ( ) ;
@@ -16,4 +19,38 @@ pub fn once_example() {
1619 println ! ( "Once: {}" , val) ;
1720 }
1821
22+ }
23+
24+ pub fn oncecell_example ( ) {
25+ let cell = OnceCell :: new ( ) ;
26+ assert ! ( cell. get( ) . is_none( ) ) ;
27+
28+ let value: & String = cell. get_or_init ( || {
29+ "Hello, World!" . to_string ( )
30+ } ) ;
31+ assert_eq ! ( value, "Hello, World!" ) ;
32+ assert ! ( cell. get( ) . is_some( ) ) ;
33+
34+ println ! ( "OnceCell: {}" , cell. get( ) . is_some( ) )
35+ }
36+
37+ pub fn oncelock_example ( ) {
38+ static CELL : OnceLock < String > = OnceLock :: new ( ) ;
39+ assert ! ( CELL . get( ) . is_none( ) ) ;
40+
41+ std:: thread:: spawn ( || {
42+ let value: & String = CELL . get_or_init ( || {
43+ "Hello, World!" . to_string ( )
44+ } ) ;
45+ assert_eq ! ( value, "Hello, World!" ) ;
46+ } ) . join ( ) . unwrap ( ) ;
47+
48+
49+ sleep ( Duration :: from_secs ( 1 ) ) ;
50+
51+ let value: Option < & String > = CELL . get ( ) ;
52+ assert ! ( value. is_some( ) ) ;
53+ assert_eq ! ( value. unwrap( ) . as_str( ) , "Hello, World!" ) ;
54+
55+ println ! ( "OnceLock: {}" , value. is_some( ) )
1956}
0 commit comments