Skip to content

Commit 6511d80

Browse files
committed
c13: add some status output
1 parent c726497 commit 6511d80

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

c13_iter_closure/src/main.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,14 @@ struct Rectangle {
1919

2020
impl Inventory {
2121
fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
22+
// closure
2223
user_preference.unwrap_or_else(|| self.most_stocked())
2324
}
2425

2526
fn most_stocked(&self) -> ShirtColor {
2627
let mut num_red = 0;
2728
let mut num_blue = 0;
28-
29+
// iterators
2930
for color in &self.shirts {
3031
match color {
3132
ShirtColor::Red => num_red += 1,
@@ -41,6 +42,8 @@ impl Inventory {
4142
}
4243

4344
fn main() {
45+
println!("#1) Give away the most in the inventory if None color selected.");
46+
4447
let store = Inventory {
4548
shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
4649
};
@@ -59,25 +62,30 @@ fn main() {
5962
user_pref2, giveaway2
6063
);
6164

65+
println!("#2) Run an expensive closure (sleeping).");
66+
6267
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));
6570
eprintln!("{:?}", num);
6671
num};
6772

68-
expensive_closure(2);
73+
let ans = expensive_closure(3);
74+
println!("Return from expensive_closure is {ans}");
6975

7076
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);
7278
let mut borrows_mutably = || list.push(7);
7379
borrows_mutably();
74-
println!("After calling closure: {:?}", list);
80+
println!("List after calling closure: {:?}", list);
7581

82+
println!("#3) Launch a thread to print list.");
7683
thread::spawn(
7784
move || println!("From thread: {:?}", list))
7885
.join()
7986
.unwrap();
8087

88+
println!("#4) Sort a list of rectangles by width.");
8189

8290
let mut list = [
8391
Rectangle { width: 10, height: 1 },

0 commit comments

Comments
 (0)