Last active
February 11, 2023 15:25
-
-
Save erhangundogan/7a141ba1ae6302c1a7af2cb7b5ea33f6 to your computer and use it in GitHub Desktop.
Rust learning very first example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
use rand::Rng; | |
fn guess_number() -> i32 { | |
let mut guess = String::new(); | |
println!("What is your guess?"); | |
io::stdin().read_line(&mut guess).expect("Could not read line"); | |
return match guess.trim().parse() { | |
Ok(n) => n, | |
Err(_e) => { | |
println!("Wrong number!"); | |
std::process::exit(1); | |
}, | |
}; | |
} | |
fn get_random_number(max: Option<i32>) -> i32 { | |
let mut rng = rand::thread_rng(); | |
return rng.gen_range(1..=max.unwrap_or(10)); | |
} | |
fn main() { | |
let max_guess_count = 3; | |
let max_value = 10; | |
println!("I pick a number between 1-{max_value}. Please guess my number. You have {max_guess_count} guesses."); | |
let my_num = get_random_number(Some(max_value)); | |
let mut count = 0; | |
let mut found = false; | |
while !found && count < max_guess_count { | |
found = my_num == guess_number(); | |
count = count + 1; | |
} | |
if found { | |
println!("That was a correct number! You guessed in {count} times."); | |
} else { | |
println!("You failed. My number was {my_num}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment