this post was submitted on 24 Dec 2024
33 points (100.0% liked)
Rust
6244 readers
16 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
The biggest/only real problem is the
.unwrap()
. This will cause the program to exit with an error message if the user inputs an invalid value. Which is not a great user experience. Better to reject the input and ask them again (aka start the loop again). You can do this with amatch
on the returned value of parse with a message and a continue onErr
(good time to learn about enums and pattern matching as well).A minor improvement can be done to this:
By replacing it with:
Which has a few advantages:
These are more nitpicks than anything substantial - would lead to nicer code in more complex situations but negligible at best in this code base (only really pointing out to give you some things to think about):
Since you break in the win condition the
attempts += 1;
can be moved out of the other branches at the same level as theinput.clear()
.Rand has a gen_range function which can be used like:
Though typically you would save the thread_rng() output to a local and reuse that throughout your program instead of creating one each time - here you only need one number so that matters less. The Rng trait has a lot more convenience function on it as well so it is generally worth using over just the
random()
function. Though in this case it makes very little difference overall here - typically you would want to opt for one of those methods instead so is worth knowing about.I dislike the name
x
as it is very ambiguous. IMO short letters should be used only in smaller scopes or when they represent some sort of mathematical value. Here I would usesecret_number
orsecret_value
or something more descriptive. Though in this case there is not a much better domain name here, more often there is.Thank you so much for the suggestion. I have updated the code locally :)