0

I'm trying to use match with a String to compare values in Rust, and i'm very beginner on rust, so idk if has a better way or other method to do this, but, it's not working well this far:

fn main() {
    println!("Enter what type of calc u want: ");

    let mut calc = String::new();

    io::stdin().read_line(&mut calc).expect("Failed to read"); // reading input

    println!("u selected: {}", calc); // this prints the input as well

    let result = match calc.as_str() {
        "sum" => sum(),
        "subtraction" => subtraction(),
        "division" => division(),
        "multiplication" => multiplication(),
        &_ => 0,
    };

    println!("{}", result); // always returning 0
}

só result is being the default value, and calc has the input value as it should, so i know it's something in match calc.as_str()

  • Does this answer your question? [Why does my string not match when reading user input from stdin?](/q/27773313/2189130) – kmdreko Oct 15 '22 at 02:34

1 Answers1

0

When you input sum in stdin, you will get sum\n. So you can do the following changes:

let result = match calc.as_str() {
    "sum\n" => sum(),
    "subtraction\n" => subtraction(),
    "division\n" => division(),
    "multiplication\n" => multiplication(),
    _ => 0,
};

Or

let result = match calc.trim() {
    "sum" => sum(),
    "subtraction" => subtraction(),
    "division" => division(),
    "multiplication" => multiplication(),
    _ => 0,
};
Changfeng
  • 49
  • 2