0

I am trying to match on a user-supplied string with this code:

use std::io;

fn main() {
    let mut input = String::new();

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

    match input.as_ref(){
        "test" => println!("That was test"),
        _ => print!("Something's wrong"),
    }
}

However, this code always prints "Something's wrong", even when I enter "test". How can I make this work as intended?

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • "this isn't working" is not a problem description. Are you getting errors? Which ones? Are you getting unexpected output? Which one did you expect? – ForceBru Dec 02 '18 at 18:33
  • 1
    try `input.trim().as_ref()` to get rid of the tailing newline – Minn Dec 02 '18 at 18:42
  • Yes, my problem is unexpected output. this code not working as i wanted. Always giving me "Somethings wrong" –  Dec 02 '18 at 19:20

1 Answers1

5

This doesn't match "test" even if (it looks like) you enter "test" because you're also inputting a new line by hitting Enter, so input will actually contain "test\n".

You can solve this by removing the trailing newline using trim_end:

match input.trim_end() {
    "test" => println!("Great!"),
    _ => println!("Too bad")
}

This won't modify the original string, though.

ForceBru
  • 43,482
  • 10
  • 63
  • 98