Я новичок в ржавчине и довольно смущен этой ошибкой типа. Вот мой код:
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 не будет содержать +-*/
.
Как это возможно?