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?

3
  • "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? Commented Dec 2, 2018 at 18:33
  • 1
    try input.trim().as_ref() to get rid of the tailing newline Commented Dec 2, 2018 at 18:42
  • Yes, my problem is unexpected output. this code not working as i wanted. Always giving me "Somethings wrong" Commented Dec 2, 2018 at 19:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks sir. This is solving my problem.