I created a rust implementation of hangman as a command line version. The user can enter characters to find out the desired word.
I really appreciate any helpful comment which highlights how I could improve the code and in particular make more "rustacean".
use std::io;
use std::collections::HashSet;
fn extract_char(line: &str) -> char{
line.trim().chars().nth(0).expect("Please input a single character.")
}
fn get_current_guess(word: &str, chars: &HashSet<char>) -> String {
word.chars().map(|x| if chars.contains(&x) {x} else {'_'}).collect()
}
fn main() {
println!("Welcome to Hangman!");
let word = "declaration";
let mut user_chars: HashSet<char> = HashSet::new();
let max_incorrect_guesses = 5;
let mut incorrect_guesses = 0;
loop {
println!("Please input a single char:");
let mut current_input = String::new();
io::stdin()
.read_line(&mut current_input)
.expect("Failed to read input.");
let current_char = extract_char(¤t_input);
if user_chars.contains(¤t_char) {
println!("You already chose {}.", current_char);
continue
}
else if !word.contains(current_char){
incorrect_guesses += 1;
println!("{} is not in word.", current_char);
println!("Number of incorrect guesses is now {}", incorrect_guesses);
}
user_chars.insert(current_char);
if incorrect_guesses > max_incorrect_guesses {
println!("You have reached the maximum number of incorrect guesses.");
println!("The correct word is {}.", word);
break
}
println!("Your current guess is {:?}", get_current_guess(&word, &user_chars));
}
}