@@ -19,13 +19,14 @@ struct Rectangle {
19
19
20
20
impl Inventory {
21
21
fn giveaway ( & self , user_preference : Option < ShirtColor > ) -> ShirtColor {
22
+ // closure
22
23
user_preference. unwrap_or_else ( || self . most_stocked ( ) )
23
24
}
24
25
25
26
fn most_stocked ( & self ) -> ShirtColor {
26
27
let mut num_red = 0 ;
27
28
let mut num_blue = 0 ;
28
-
29
+ // iterators
29
30
for color in & self . shirts {
30
31
match color {
31
32
ShirtColor :: Red => num_red += 1 ,
@@ -41,6 +42,8 @@ impl Inventory {
41
42
}
42
43
43
44
fn main ( ) {
45
+ println ! ( "#1) Give away the most in the inventory if None color selected." ) ;
46
+
44
47
let store = Inventory {
45
48
shirts : vec ! [ ShirtColor :: Blue , ShirtColor :: Red , ShirtColor :: Blue ] ,
46
49
} ;
@@ -59,25 +62,30 @@ fn main() {
59
62
user_pref2, giveaway2
60
63
) ;
61
64
65
+ println ! ( "#2) Run an expensive closure (sleeping)." ) ;
66
+
62
67
let expensive_closure = |num : u32 | -> u32 {
63
- eprint ! ( "calculating slowly..." ) ;
64
- thread:: sleep ( Duration :: from_secs ( 2 ) ) ;
68
+ eprint ! ( "Calculating slowly (sleep {num} seconds) ..." ) ;
69
+ thread:: sleep ( Duration :: from_secs ( num as u64 ) ) ;
65
70
eprintln ! ( "{:?}" , num) ;
66
71
num} ;
67
72
68
- expensive_closure ( 2 ) ;
73
+ let ans = expensive_closure ( 3 ) ;
74
+ println ! ( "Return from expensive_closure is {ans}" ) ;
69
75
70
76
let mut list = vec ! [ 1 , 2 , 3 ] ;
71
- println ! ( "Before defining closure: {:?}" , list) ;
77
+ println ! ( "List before defining & calling closure that modifies the list : {:?}" , list) ;
72
78
let mut borrows_mutably = || list. push ( 7 ) ;
73
79
borrows_mutably ( ) ;
74
- println ! ( "After calling closure: {:?}" , list) ;
80
+ println ! ( "List after calling closure: {:?}" , list) ;
75
81
82
+ println ! ( "#3) Launch a thread to print list." ) ;
76
83
thread:: spawn (
77
84
move || println ! ( "From thread: {:?}" , list) )
78
85
. join ( )
79
86
. unwrap ( ) ;
80
87
88
+ println ! ( "#4) Sort a list of rectangles by width." ) ;
81
89
82
90
let mut list = [
83
91
Rectangle { width : 10 , height : 1 } ,
0 commit comments