Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust - true or false

Tags:

boolean

rust

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;
    }
}
like image 941
Gkey Avatar asked Aug 26 '26 16:08

Gkey


2 Answers

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.

like image 119
Nathaniel Ford Avatar answered Aug 29 '26 18:08

Nathaniel Ford


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)

like image 30
L. F. Avatar answered Aug 29 '26 17:08

L. F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!