Number Guessing Game
Level: intro (score: 1)
Imagine you're playing a guessing game where the secret number is hidden—and sometimes the input isn't quite right.
In this exercise, you'll implement a function that iterates over a list of guesses (provided as strings) using a while
loop.
Your function should follow these rules:
- Each guess is a &str
.
- If a guess is the string "STOP"
, immediately exit the loop (using break
) and return None
(the game is aborted).
- If a guess cannot be parsed into a number, skip that guess (using continue
) without counting it as an attempt.
- For valid numeric guesses, count them as attempts. If a valid guess equals the secret, return Some(attempt_count)
, where attempt_count
is the number of valid attempts made.
- If the loop finishes without finding the secret, return None
.
Hints:
- Use a while
loop to iterate through the slice.
- Use g.parse::<u32>()
to try to convert a guess into a number.
- Use continue
to skip invalid (no number) guesses, and break
when you encounter "STOP"
.
- Use mutable variables (declared with let mut
) to keep track of the current index and the number of valid attempts.
- Use the match
construct to attempt parsing each guess into a number. In Rust, match
is a powerful control-flow operator that lets you branch based on pattern matching—here it helps decide whether the parsing was successful (Ok(num)
) or not (Err(_)
).
And that's it, your first simple game in Rust! 🎉 🦀