How can I match a string read from standard input?
In an exercise to learn Rust, I try a simple program that will take your name and then print your name if it is valid.
Only "Alice" and "Bob" are valid names.
use std::io;
fn main() {
println!("What your name?");
let mut name = String::new();
io::stdin().read_line(&mut name)
.ok()
.expect("Failed to read line");
greet(&name);
}
fn greet(name: &str) {
match name {
"Alice" => println!("Your name is Alice"),
"Bob" => println!("Your name is Bob"),
_ => println!("Invalid name: {}", name),
}
}
When I use cargo run
this main.rs
file, I get:
What your name?
Alice
Invalid name: Alice
Now, I think because "Alice" is of type &'static str
and name
is of type &str
, it may not match correctly ...
+3
source to share
1 answer
I'm pretty sure this is not caused by a type mismatch. I am betting that there are some invisible characters (newline) in this case. To achieve your goal, you must truncate the input line:
match name.trim() {
"Alice" => println!("Your name is Alice"),
"Bob" => println!("Your name is Bob"),
_ => println!("Invalid name: {}", name),
}
+6
source to share