Files
rust-book-walkthrough/guessing-game/src/main.rs
T

62 lines
2.5 KiB
Rust

// We import io from the standard library
// It is like stdin stdout stderr and all that
use std::cmp::Ordering;
use std::io;
use rand::Rng;
// Main entry point of application
fn main() {
// Use the println! macro to print to stdout
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("Please input your guess.");
// here we start the while ish loop
loop {
// uncomment the next line if you want to see the secret number as stdout
// println!("The secret number is {secret_number}");
// declare a mutable variable which is a growable empty string
let mut guess = String::new();
// from io in the std lib use stdin as input to app
// use read_line to read the input and stores it in a reference to the mutable variable guess
// Then expect is used as err handling, if something goes wrong, write to stderr and quit
// program with 1
io::stdin()
.read_line(&mut guess)
.expect("failed to read line");
// In rust, when converting types, you usually use the same var name, instead of doing something
// like let guess_int and let guess_str.
// here we define guess as unsigned 32 bit int, we reuse the guess variable, then we do a trim
// of it, because user input can contain 4\n which would cause it to fail always, as it cannot
// be parsed to an int. The parse step knows that it should parse it to the defined u32 data type.
// The expect has the result of either error or ok, and terminates the program if not valid
// integer.
// So here the expect is exchanged with match and pattern matching with the two result
// values, "Ok" and "Err". This is for gracefull err handling and starting the while loop
// again, even if you enter something invalid.
// Parse returns Result as mentioned above, but also "num" which is the Ok number
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// print the user input with extrapolated guess variable in {} brackets
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}