rust - 真或假

标签 rust boolean

如何正确读取用户输入的字符串('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 变量将是一个 boolean 值。通常,这种功能嵌入在 FromStr 实现中,但严格来说并非如此。

关于 rust - 真或假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68505340/

相关文章:

rust - 使用 Serde 序列化值时如何执行额外的数据库查询?

rust - 如何存储实现共同特征的结构(不是实例)?

loops - 如何使用 Tokio 在每个周期或间隔(以秒为单位)触发功能?

rust - 从子结构中获取值,然后修改子结构 : a borrow checker puzzle?

rust - 我需要推送 (Vec) 包含的结构成员,他也是一个结构

c++ - 在 C++ 中难以掌握简单的 boolean 循环 if/else 程序

boolean - 简化 boolean 方程

java - 从插入函数等返回 boolean 值的正确方法是什么?

python - "banana"< "orange"为真,"banana"< "Orange"为假,但为什么呢?

java - 将包含 boolean 值的文本文件作为对象读取到数组列表中