简体   繁体   中英

Why is there a mismatched types error when comparing a value after parsing it from a string?

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."),
    };
}

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."),
    };
}

playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM