首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么在从字符串中解析一个值之后比较它时会出现类型不匹配错误?

为什么在从字符串中解析一个值之后比较它时会出现类型不匹配错误?
EN

Stack Overflow用户
提问于 2019-09-10 01:20:56
回答 1查看 77关注 0票数 0

我不明白为什么在成功解析后比较两个值时会出现类型不匹配错误。我的大部分工作都是使用动态语言完成的,所以这可能会让我感到困惑。在C++或C#这样的另一种语言中会发生这种情况吗?

此代码无效。

代码语言:javascript
运行
复制
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."),
    };
}
代码语言:javascript
运行
复制
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}`

而这个代码是有效的。

代码语言:javascript
运行
复制
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."),
    };
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-10 03:14:13

您的问题实际上是由于在匹配分支中使用了错误的变量。在任何静态类型的语言中,这都是一个编译时错误。

当您在Ok(i)上对match进行模式匹配时,您会说“在Ok中包装了一些变量--我将把这个变量称为i,并在这个match分支范围内对它执行一些操作。”

你想要的是:

代码语言:javascript
运行
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57858548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档