【问题标题】:Rust mismatched type error for outside of loop循环外的 Rust 类型不匹配错误
【发布时间】:2020-01-19 06:35:51
【问题描述】:

我是 rust 新手,对这种类型的错误感到很困惑。 这是我的代码:

use std::io::{stdin, stdout, Write};

fn read(input: &mut String) {
    stdout().flush().expect("failed to flush");
    stdin().read_line(input).expect("failed to read");
}

fn main() {
    let mut num1 = String::new();
    let mut num2 = String::new();

    println!("what is the first number?");
    read(&mut num1);
    println!("what is the second number?");
    read(&mut num2);
    let mut operator = String::new();

    loop {
        println!("what is the operator[+-*/?]");
        read(&mut operator);
        let operator: char = operator.trim().chars().next().unwrap();
        let operators = String::from("+-*/");
        if !operators.contains(operator) {
            println!("unknown operator!!");
        } else {
            break;
        };
    }

    let num1: f32 = num1.trim().parse().unwrap();
    let num2: f32 = num2.trim().parse().unwrap();

    let result = match operator {
        '+' => num1 + num2,
        '-' => num1 - num2,
        '*' => num1 * num2,
        '/' => num1 / num2,
        _ => panic!("error in operator"),
    };

    println!("the result is {}{}{} = {} ", num1, operator, num2, result);
}

这是来自 rust 编译器的错误:

error[E0308]: mismatched types
  --> src/main.rs:34:9
   |
34 |         '+' => num1 + num2,
   |         ^^^ expected struct `std::string::String`, found char
   |
   = note: expected type `std::string::String`
              found type `char`

error[E0308]: mismatched types
  --> src/main.rs:35:9
   |
35 |         '-' => num1 - num2,
   |         ^^^ expected struct `std::string::String`, found char
   |
   = note: expected type `std::string::String`
              found type `char`

error[E0308]: mismatched types
  --> src/main.rs:36:9
   |
36 |         '*' => num1 * num2,
   |         ^^^ expected struct `std::string::String`, found char
   |
   = note: expected type `std::string::String`
              found type `char`

error[E0308]: mismatched types
  --> src/main.rs:37:9
   |
37 |         '/' => num1 / num2,
   |         ^^^ expected struct `std::string::String`, found char
   |
   = note: expected type `std::string::String`
              found type `char`

我猜我收到错误的原因是因为 operator 的类型已从 String 更改为 char 但我想使用循环直到 stdin 的输入包含 +-*/

这怎么可能?

【问题讨论】:

标签: rust


【解决方案1】:

这个程序有一个小错误。您在两个不同的范围内定义了两次运算符。在外部范围内是String,在内部范围内是char。您在外部范围内使用了match 运算符,它是String,但您已匹配char

小调整,这里是链接Playground

【讨论】:

  • 谢谢它的工作,但它仍然让我对“未知操作员!!”的输出感到困惑即使我输入了其中一个运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2019-12-03
  • 2014-08-13
  • 1970-01-01
相关资源
最近更新 更多