Gkey
Gkey

Reputation: 85

Rust - true or false

How does one properly read from user input a string ('true' or 'false') as bool - true or false, and do something with that? Without this primitive way by using 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;
    }
}

Upvotes: 6

Views: 13962

Answers (2)

L. F.
L. F.

Reputation: 20579

Rust has a native FromStr implementation for many types, including bool, that is frequently invoked via str::parse:

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

This implementation only matches on the exact strings "true" and "false", so it is more suitable for deserialization than user interaction. In particular, it is necessary to remove the newline at the end of condition (using .trim()) before parsing.

The use of unwrap here is for demonstration only — see the Error Handling chapter of The Rust Programming Language for more on the information on error handling in Rust.


After you become more familiar with Rust, you can use crates like dialoguer to render select prompts:

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(())
}

(using anyhow for error handling)

Upvotes: 9

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

You probably want something like this:

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.
}

Then you truth_value variable will be a boolean. Typically this sort of functionality is embedded in a FromStr implementation, but it needn't be, strictly speaking.

Upvotes: 9

Related Questions