use std::io; use rand::Rng; use std::cmp::Ordering; fn main() { println!("Hello, world!"); println!("Guess the Number!"); println!("Input the number here:"); let rng_num = rand::thread_rng().gen_range(1..101); loop { let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {}", guess); // Parse guess string into number //let guess: i32 = guess.trim().parse().expect("PleaseType a number!"); let guess: i32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue // _ means any value }; // Instead of Running an exception and crashing the program, we can setup a match expression // This expression will parse the Result from the function last called (Enum based) // On an Ok it will return the result of the function which is num // On an Error it will do another thing // We transform the mutable string into unmutable integer value // Match expression is based on the result of a comparison // each statement between commas, is a possible branch (like a switch based on an Enum Result) // It is like a switch that only executes a single part not sequencially match guess.cmp(&rng_num) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal =>{ println!("You win!"); break; // Get out of guess loop } } } println!("Secret number was {}", rng_num); }