rust - 如何调试一些 Rust 代码以找出“if”语句不运行的原因?
问题描述
这段代码是我通过查看“Hands-on Rust”一书制作的,它基本上是“搜索数组”部分的代码副本。我不知道为什么“如果有效”语句没有运行,即使变量应该设置为 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
}
}
如果让您生气,请原谅荒谬的评论数量。我这样做是为了找出不好的部分在哪里。
解决方案
有一个非常酷的宏,叫做dbg!
我喜欢使用。这就像println!
类固醇。您可以将它包装在几乎任何变量、表达式甚至子表达式周围,它会打印其中的代码、值和源位置。
让我们将它添加到循环中,看看发生了什么:
for key in &key_list {
if dbg!(key) == dbg!(&enter) {
valid = true
}
};
这是我看到的:
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"
啊! enter
实际上并没有被修剪。它仍然有尾随的换行符。嗯,这是为什么呢?我们来看看trim
方法:
pub fn trim(&self) -> &str
看起来它返回一个新&str
切片而不是修改输入字符串。我们知道它不能就地改变它,因为它不需要&mut self
.
to_lowercase
是一样的:
pub fn to_lowercase(&self) -> String
修复:
let enter = enter.trim().to_lowercase();
推荐阅读
- android - 使用服务用片段膨胀活动
- download - 下载 blob 网址
- postgresql - 包装函数抛出“查询没有结果数据的目的地”错误
- javascript - 如何在 TinyMce 的预代码块中保留跨度标签和类
- javascript - 将图像从烧瓶发送到 js 文件
- django - Django 错误:user_register_model 匹配查询不存在
- r - 根据列的值重复data.table中的行
- wxpython - 如何使用 Inno_setup 添加我的可执行文件的自动更新
- linux - 将 GUNZIP 连接到 GREP
- android - 如何将图像从 Webview 下载到自定义/私有文件夹而不是 Android 中的下载文件夹