这段代码是我根据《Hands-on Rust》一书中“在数组中搜索”的部分编写的,基本上是从那里复制的。我不知道为什么“if valid”语句没有运行,即使变量应该设置为 true。
use std::io::stdin;
fn main() {
println!("Please enter the key"); //prints the string
let mut enter = String::new(); //initiates the changeable variable "enter"
stdin().read_line(&mut enter).expect(r#"invalid key"#); //allows user input and reads the input to assign into the "enter" variable
enter.trim().to_lowercase(); //trims the "enter" variable out of non-letter inputs and turns them into lowercase
let key_list = ["1", "2", "3"]; //the input needed to get the desired output
let mut valid = false; //initiates the "valid" variable to false
for key in &key_list { //runs the block of code for each item in the "key_list" array
if key == &enter { //runs the block of code if the variable "enter" matches the contents of the array "key_list"
valid = true //turns the "valid" variable into true
}
};
if valid { //it will run the block of code if the variable valid is true
println!("very nice, {}", enter) //it prints the desired output
} else { //if the if statement does not fulfill the condition, the else statement's block of code will run
println!("key is either incorrect or the code for this program sucks, your input is {}", enter) //the failure output
}
}
如果我的大量注释让你感到不舒服,请见谅。我这样做是为了找出错误所在。