![](/img/trans.png)
[英]Returning a value from within an if statement has a “mismatched types” error
[英]Why is there a mismatched types error when comparing a value after parsing it from a string?
我不明白為什么在成功解析后比較兩個值時會出現類型不匹配錯誤。 我的大部分工作都是使用動態語言完成的,因此這可能會讓我失望。 這會在其他語言(例如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."),
};
}
您的問題實際上是由於在您的匹配分支中使用了錯誤的變量。 這將是任何靜態類型語言的編譯時錯誤。
當您在Ok(i)
上對匹配進行模式化時,您會說:“在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."),
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.