简体   繁体   English

为什么我的 Rust 程序总是进入 while 循环而从不退出

[英]why my Rust program always enters while loop and never exits

I am reading through the Rust book and doing the optinal exercise along the way.我正在阅读 Rust 这本书,并在此过程中进行了可选练习。 I've finished the chapter 8 (Common Collections) and am trying the last exercise.我已经完成了第 8 章(Common Collections),并且正在尝试最后一个练习。 The exercise instructions are:练习指导如下:

Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company.使用 hash map 和向量,创建一个文本界面以允许用户将员工姓名添加到公司的部门。 For example, “Add Sally to Engineering” or “Add Amir to Sales.”例如,“将 Sally 添加到工程”或“将 Amir 添加到销售”。 Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.然后让用户按部门检索一个部门中所有人员或公司所有人员的列表,按字母顺序排序。

What I want my program to do is firstly ask the user if they want to add a new employee, if no, the program ends else it allows them to continously add an employee until the user declines to add any more.我想要我的程序做的是首先询问用户是否要添加新员工,如果没有,程序结束,否则它允许他们不断添加员工,直到用户拒绝添加。

I've chosen to simply start with the initial user prompt asking if they want to add a new employee.我选择简单地从初始用户提示开始,询问他们是否要添加新员工。 I start with an empty String for the user input, once the user enters their response there is a while loop that repeats until the user enters a valid response ( [Y/n] ).我从用户输入的空String开始,一旦用户输入他们的响应,就会有一个 while 循环重复,直到用户输入有效的响应( [Y/n] )。 Since the condition for the while loop is when the response is not equal to "y" or "n" I expected correct responses to skip the while loop but instead the while loop is always entered and never exited no matter what.由于 while 循环的条件是当响应不等于"y""n"时,我希望正确的响应跳过 while 循环,而是始终进入 while 循环并且无论如何都不会退出。 Since I'm new to Rust I'm not sure if there some obvious or idiosyncratic reason for this behaviour.由于我是 Rust 的新手,我不确定这种行为是否有一些明显或特殊的原因。 I'll also add that I remove whitespace (incl. \n ) from the response and make the response lowercase in the while loop condition, all of which can be seen in my code below.我还要补充一点,我从响应中删除了空格(包括\n ),并在 while 循环条件中使响应小写,所有这些都可以在下面的代码中看到。

use std::collections::{HashMap, HashSet};
use std::io;

const DEPARTMENT: [&str; 5] = ["Engineering", "IT", "Sales", "Marketing", "HR"];

fn main() {
    // Initialize company roster
    let mut company: HashMap<String, HashSet<String>> = HashMap::new();
    for key in DEPARTMENT.iter() {
        company.insert((*key).to_string(), HashSet::new());
    }
    // println!("{:?}", company);

    let mut response = String::new();

    // Prompt user to add a new employee or not
    print!("Would you like to add an employee to the company roster? [Y/n] ");
    io::stdin().read_line(&mut response).expect("Failed to read line.");
    remove_whitespace(&mut response);

    // Ensure response is valid
    while response.to_lowercase() != "y" || response.to_lowercase() != "n" {
        response.drain(..);
        println!();
        print!("Please respond to the previous question with either 'y' or 'n' (case insensitive): ");
        io::stdin().read_line(&mut response).expect("Failed to read line.");
        remove_whitespace(&mut response);
        // print!("\n{}", response.to_lowercase() == "y" || response.to_lowercase() == "n");
    }
}

fn remove_whitespace(s: &mut String) {
    s.retain(|c| !c.is_whitespace());
}

I'd appreciate any assistance to help me understand why the program doesn't do what I expect.我很感激任何帮助,以帮助我理解为什么该程序没有达到我的预期。

Check your while conditions (it is always true), and what you wrote检查您的 while 条件(始终为真)以及您写的内容

"loop is when the response is not equal to "y" or "n"" “循环是当响应不等于“y”或“n”时

means in pseudo code伪代码中的意思

NOT (answer = "y" OR answer="n")不是(答案=“y”或答案=“n”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM