【发布时间】: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 的输入包含 +-*/。
这怎么可能?
【问题讨论】:
-
a simple solution 但你的代码不会做你想做的事。
标签: rust