Reputation: 13
I don't understand why I get a type mismatch error when comparing two values after a successful parse. Most of my work has been done using dynamic languages so maybe this is throwing me off. Would this happen in another language such a C++ or C#?
This code is invalid.
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}`
While this code is valid.
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."),
};
}
Upvotes: 0
Views: 729
Reputation: 301
Your problem is actually due to using the wrong variable in your match branches. This would be a compile-time error in any statically typed language.
When you pattern match on Ok(i)
you are saying "there is some variable wrapped within an Ok
-- I am going to call this variable i
and do something with it inside of this match branch scope."
What you want is:
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."),
};
}
Upvotes: 1