我不明白为什么在成功解析后比较两个值时会出现类型不匹配错误。我的大部分工作都是使用动态语言完成的,所以这可能会让我感到困惑。在C++或C#这样的另一种语言中会发生这种情况吗?
此代码无效。
use std::io;
fn main() {
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("Failed to read line");
let num_of_books = input_text.trim();
match num_of_books.parse::<u32>() {
Ok(i) => {
if num_of_books > 4 {
println!("Wow, you read a lot!");
} else {
println!("You're not an avid reader!");
}
}
Err(..) => println!("This was not an integer."),
};
}error[E0308]: mismatched types
--> src/main.rs:12:31
|
12 | if num_of_books > 4 {
| ^ expected &str, found integer
|
= note: expected type `&str`
found type `{integer}`而这个代码是有效的。
use std::io;
fn main() {
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("Failed to read line");
let num_of_books = input_text.trim();
match num_of_books.parse::<u32>() {
Ok(i) => {
if num_of_books > "4" {
println!("Wow, you read a lot!");
} else {
println!("You're not an avid reader!");
}
}
Err(..) => println!("This was not an integer."),
};
}发布于 2019-09-10 03:14:13
您的问题实际上是由于在匹配分支中使用了错误的变量。在任何静态类型的语言中,这都是一个编译时错误。
当您在Ok(i)上对match进行模式匹配时,您会说“在Ok中包装了一些变量--我将把这个变量称为i,并在这个match分支范围内对它执行一些操作。”
你想要的是:
use std::io;
fn main() {
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("Failed to read line");
let num_of_books = input_text.trim();
match num_of_books.parse::<u32>() {
Ok(i) => {
if i > 4 {
println!("Wow, you read a lot!");
} else {
println!("You're not an avid reader!");
}
}
Err(..) => println!("This was not an integer."),
};
}https://stackoverflow.com/questions/57858548
复制相似问题