简体   繁体   English

从字符串解析后的值进行比较时,为什么会有类型不匹配的错误?

[英]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#? 这会在其他语言(例如C ++或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." 当您在Ok(i)上对匹配进行模式化时,您会说:“在Ok内包装了一些变量-我将调用此变量i并在此match分支作用域内对其执行某些操作。”

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 游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从if语句中返回值时出现“类型不匹配”错误 - Returning a value from within an if statement has a “mismatched types” error 索引&str时出现“错误:类型不匹配” - “error: mismatched types” when indexing a &str 从os :: args调用from_str上的字符串时类型不匹配 - Mismatched types when calling from_str on a String from os::args “不匹配的类型预期单元类型`()`找到枚举`选项<String> `&quot; 尝试使用 Tauri 读取文件内容时出错 - "mismatched types expected unit type `()` found enum `Option<String>`" Error when trying to read the content of a file with Tauri 为什么在使用 TryFuture 而不是等效的 Future 时会收到关于类型不匹配的错误? - Why do I get an error about mismatched types when using TryFuture instead of the equivalent Future? 类型不匹配:在分配字符串时预期&str找到了字符串 - Mismatched types: expected &str found String when assigning string 如何解决涉及从 Rust 中的结构获取值的引用的不匹配类型错误 - How to resolve mismatched types error around reference that involves getting a value from a struct in Rust 在 STDIN 之后编译时获取不匹配的类型,然后对输入进行数学运算 - Getting mismatched types when compiling after STDIN and then math on input 为什么我的猜谜游戏会产生“类型不匹配”错误? - Why does my guessing game produce a "mismatched types" error? 插入HashMap &lt;&str,u64&gt;时出现类型不匹配错误 - Mismatched types error when inserting into a HashMap<&str, u64>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM