我正在尝试获取用户输入,并检查用户是否输入了“ y”或“ n”。令人惊讶的是,在下面的代码中,the if
和if else
case 都不执行!显然,correct_name
既不是“ y”也不是“ n”。这个怎么可能?我是在做字符串转换错误还是什么?
use std::io;
fn main() {
let mut correct_name = String::new();
io::stdin().read_line(&mut correct_name).expect("Failed to read line");
if correct_name == "y" {
println!("matched y!");
} else if correct_name == "n" {
println!("matched n!");
}
}
read_line
在返回的字符串中包含终止换行符。添加.trim_right_matches("\r\n")
到的定义correct_name
以删除终止的换行符。
那么Windows,应该是“ \ r \ n”吗?
当我添加它时,它告诉我没有为`&str类型实现bool`
在查看文档后,我意识到它必须放在if语句中。谢谢!
您不需要
as_slice
,因为String
工具Deref<Target=str>
。let line = io::stdin().read_line(); let trimmed = line.trim_right_chars(..);
应该管用。而且我建议您使用just
trim
或trim_right
而不是担心跨平台的换行符:-)