4 rust
这段代码是我根据《Hands-on Rust》一书编写的,它基本上是“搜索数组”部分代码的副本。我不知道为什么即使变量应该设置为 true,“if valid”语句也不会运行。
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果评论数量如此之多,让您感到烦恼,请原谅。我这样做是为了尝试找出问题所在。
Joh*_*ica 11
有一个非常酷的宏,叫做dbg!我喜欢使用。就像println!服用类固醇一样。您可以将它包装在几乎任何变量、表达式甚至子表达式周围,它会打印其中的代码、值和源位置。
让我们将其添加到循环中,看看发生了什么:
for key in &key_list {
if dbg!(key) == dbg!(&enter) {
valid = true
}
};
Run Code Online (Sandbox Code Playgroud)
这是我所看到的:
Please enter the key
1
[src/main.rs:10] key = "1"
[src/main.rs:10] &enter = "1\n"
[src/main.rs:10] key = "2"
[src/main.rs:10] &enter = "1\n"
[src/main.rs:10] key = "3"
[src/main.rs:10] &enter = "1\n"
Run Code Online (Sandbox Code Playgroud)
啊! enter实际上并没有被修剪。它仍然有尾随的换行符。嗯,这是为什么呢?我们来看看trim方法:
pub fn trim(&self) -> &str
Run Code Online (Sandbox Code Playgroud)
看起来它返回一个新&str切片而不是修改输入字符串。我们知道它不能就地改变它,因为它不需要&mut self.
to_lowercase是一样的:
pub fn to_lowercase(&self) -> String
Run Code Online (Sandbox Code Playgroud)
修复:
let enter = enter.trim().to_lowercase();
Run Code Online (Sandbox Code Playgroud)
问题是stdin().read_line()返回带有尾随换行符的输入,但str.trim()并str.to_lowercase()不会改变原始的str. 您必须将其分配回enter:
enter = enter.trim().to_lowercase();
Run Code Online (Sandbox Code Playgroud)
println!("your input is {:?}", enter)您可以通过使用Debug格式说明符打印或约翰的答案中建议的其他选项来发现它。