Skip to content

Commit 6f8d660

Browse files
committed
refactor(guessing_game): renamed guessing_game to 02_guessing_game
1 parent ab62a3d commit 6f8d660

4 files changed

Lines changed: 20 additions & 15 deletions

File tree

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,17 +109,21 @@ let guess: u32 = match guess.trim().parse() {
109109
- `Ok(num)` - successful parse, extract the number
110110
- `Err(_)` - parse failed, prompt again
111111

112-
**Conditional Logic with `if/else if/else`**:
112+
**Conditional Logic with `match` and `Ordering`**:
113113
```rust
114-
if guess < secret_number {
115-
println!("Too low! Try again.");
116-
} else if guess > secret_number {
117-
println!("Too high! Try again.");
118-
} else {
119-
println!("Congratulations!");
120-
break; // Exit the loop
114+
use std::cmp::Ordering;
115+
116+
match guess.cmp(&secret_number) {
117+
Ordering::Less => println!("Too low! Try again."),
118+
Ordering::Greater => println!("Too high! Try again."),
119+
Ordering::Equal => {
120+
println!("Congratulations! You guessed the correct number: {}", secret_number);
121+
break; // Exit the loop - without this, the game never ends!
122+
}
121123
}
122124
```
125+
- Uses `cmp()` method to compare two values, returning an `Ordering` enum
126+
- `break` is **essential** - without it, the infinite loop continues even after winning
123127

124128
**Early Loop Continuation with `continue`**:
125129
- Used for input validation (invalid number or out of bounds)
Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::cmp::Ordering;
12
use rand::Rng;
23
use std::io;
34
use std::any::type_name;
@@ -34,13 +35,13 @@ fn main() {
3435
continue;
3536
}
3637

37-
if guess < secret_number {
38-
println!("Too low! Try again.");
39-
} else if guess > secret_number {
40-
println!("Too high! Try again.");
41-
} else {
42-
println!("Congratulations! You guessed the correct number: {}", secret_number);
43-
break;
38+
match guess.cmp(&secret_number) {
39+
Ordering::Less => println!("Too low! Try again."),
40+
Ordering::Greater => println!("Too high! Try again."),
41+
Ordering::Equal => {
42+
println!("Congratulations! You guessed the correct number: {}", secret_number);
43+
break;
44+
}
4445
}
4546
}
4647
}

0 commit comments

Comments
 (0)