如何匹配从标准输入读取的字符串? [英] How do I match on a string read from standard input?
问题描述
在学习 Rust 的练习中,我正在尝试一个简单的程序,该程序将接受您的姓名,然后在有效时打印您的姓名.
In an exercise to learn Rust, I'm trying a simple program that will accept your name, then print your name if it's Valid.
只有Alice"和Bob"是有效的名字.
use std::io;
fn main() {
println!("What's 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),
}
}
当我cargo run
这个main.rs
文件时,我得到:
When I cargo run
this main.rs
file, I get:
What's your name?
Alice
Invalid name: Alice
现在,我的猜测是,因为Alice"的类型是 &'static str
而 name
的类型是 &str
, 可能是匹配不正确...
Now, my guess is, because "Alice" is of type &'static str
and name
is of type &str
, maybe it's not matching correctly...
推荐答案
我敢打赌这不是由类型不匹配引起的.我打赌有一些不可见的字符(在这种情况下是新行).为了实现您的目标,您应该修剪输入字符串:
I bet that it isn't caused by type mismatch. I place my bet on that there are some invisible characters (new line in this case). To achieve your goal you should trim your input string:
match name.trim() {
"Alice" => println!("Your name is Alice"),
"Bob" => println!("Your name is Bob"),
_ => println!("Invalid name: {}", name),
}
这篇关于如何匹配从标准输入读取的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!