首页 > 解决方案 > 如何调试一些 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
    }
}

如果让您生气,请原谅荒谬的评论数量。我这样做是为了找出不好的部分在哪里。

标签: rust

解决方案


有一个非常酷的宏,叫做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();

推荐阅读