生锈 - 真或假

Rust - true or false

如何正确地从用户输入的字符串('true' 或 'false')中读取为 bool - true 或 false,并对其进行处理?没有这种使用 len()?

的原始方式
fn main() {
    loop {
        println!("Input condition - true or false");

        let mut condition = String::new();

        io::stdin()
            .read_line(&mut condition)
            .expect("failed to read input.");

        let len = calculate_length(&condition);

        // println!("The length of '{}' is {}.\n", &condition, &len);

        fn calculate_length(condition: &String) -> usize {
            condition.len()
        }

        match len == 5 {
            true => {
                let number = 100;
                println!("The value of number is: {}", &number);
            }

            _ => {
                let number = 7;
                println!("The value of number is: {}", &number);
            }
        };

        break;
    }
}

您可能想要这样的东西:

let truth_value: bool = match condition {
   "true" => true,
   "t" => true,
   "false" => false,
   "f" => false,
   ... any other cases you want
   _ => false  // Or whatever appropriate default value or error.
}

然后你 truth_value 变量将是一个布尔值。通常,此类功能嵌入到 FromStr 实现中,但严格来说,它不需要。

Rust 有许多类型的本机 FromStr 实现,包括 bool,经常通过 str::parse:

调用
if condition.trim().parse().unwrap() {
    // true branch
} else {
    // false branch
}

此实现仅匹配确切的字符串 "true""false",因此比用户交互更适合反序列化。特别是在解析前需要去掉condition末尾的换行符(使用.trim())。

此处 unwrap 的使用仅用于演示 — 有关 Rust 中错误处理的更多信息,请参阅 the Error Handling chapter of The Rust Programming Language


在你熟悉 Rust 之后,你可以使用像 dialoguer 这样的 crates 来渲染 select 提示:

use dialoguer::Select;

fn main() -> anyhow::Result<()> {
    let selection = Select::new().item("Choice 1").item("Choice 2").interact()?;

    match selection {
        0 => eprintln!("Choice 1 was selected."),
        1 => eprintln!("Choice 2 was selected."),
        _ => unreachable!(),
    }

    Ok(())
}

(使用 anyhow 进行错误处理)