Rust 如何匹配从标准输入读取的字符串?
在一个学习Rust的练习中,我正在尝试一个简单的程序,它将接受你的名字,然后打印你的名字,如果它是有效的 只有“Alice”和“Bob”是有效名称。Rust 如何匹配从标准输入读取的字符串?,rust,Rust,在一个学习Rust的练习中,我正在尝试一个简单的程序,它将接受你的名字,然后打印你的名字,如果它是有效的 只有“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
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),
}
}
当我运行这个main.rs
文件时,我得到:
What's your name?
Alice
Invalid name: Alice
现在,我的猜测是,因为“Alice”是类型
&'static str
,而name
是类型&str
,可能它没有正确匹配…我打赌这不是由类型不匹配引起的。我打赌有一些看不见的字符(本例中为新行)。为了实现目标,您应该修剪输入字符串:
match name.trim() {
"Alice" => println!("Your name is Alice"),
"Bob" => println!("Your name is Bob"),
_ => println!("Invalid name: {}", name),
}
尝试
匹配name.trim(){…}
。我现在无法测试,但我打赌输入中有一个换行符。就是这样。。。我总是忘记那件事,谢谢!如果你发布一个答案,我将投票并接受。如果存在类型不匹配,它将不会编译。通过使用Debug({:?}
)而不是Display({}
)格式化字符串,您也可以精确地看到字符串中的内容。我还没有提交答案,所以我会接受你的。