Ошибка несоответствия типов ржавчины за пределами цикла - PullRequest
1 голос
/ 19 января 2020

Я новичок в ржавчине и довольно смущен этой ошибкой типа. Вот мой код:

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);
}

, а вот ошибка от ржавого компилятора:

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, но я хотел бы использовать l oop, пока ввод от stdin не будет содержать +-*/.

Как это возможно?

1 Ответ

0 голосов
/ 19 января 2020

В этой программе есть небольшая ошибка. Вы определили оператор дважды в двух разных областях. Во внешней области это String, а во внутренней области это char. Вы использовали оператор match во внешней области видимости, где он равен String, но вы выбрали char.

Небольшая настройка, и вот ссылка Детская площадка

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...