[英]mismatched types expected `i8`, found `()`
I am trying to make a temperature converter in Rust, but for some reason my code here gives me an error.我正在尝试在 Rust 中制作温度转换器,但由于某种原因,我的代码在这里给了我一个错误。 I am trying to convert the choice
String
to an i8
type.我正在尝试将选择
String
转换为i8
类型。
use std::io;
fn main() {
println!("Welcome! Would you like to convert from (1) Fahrenheit to Celsius, or (2) from Celsius to Fahrenheit?");
let mut choice = String::new();
io::stdin()
.read_line(&mut choice)
.expect("Failed to read line");
println!("{}", choice);
let choice: i8 = match choice.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid input, please input a number.");
}
};
}
fn convert_to_c(f_temp: f64) {
let mut c_temp: f64;
c_temp = f_temp - 32.0 * 0.5556;
println!("{}F in Celsius is: {}", f_temp, c_temp);
}
fn convert_to_f(c_temp: f64) {
let mut f_temp: f64;
f_temp = c_temp * 1.8 + 32.0;
println!("{}C in Fahrenheit is: {}", c_temp, f_temp);
}
error[E0308]: mismatched types
--> src/main.rs:15:19
|
15 | Err(_) => {
| ___________________^
16 | | println!("Invalid input, please input a number.");
17 | | }
| |_________^ expected `i8`, found `()`
The problem is that this match statement is an expression that has to return an i8
to assign to choice
, but the Err
arm doesn't return an i8
.问题是这个 match 语句是一个表达式,它必须返回一个
i8
来分配给choice
,但是Err
arm 不返回一个i8
。
let choice: i8 = match choice.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid input, please input a number.");
}
};
One way to get it to run, is to have the Err branch panic so it never returns at all.让它运行的一种方法是让 Err 分支恐慌,这样它就永远不会返回。
Err(_) => {
println!("Invalid input, please input a number.");
panic!();
}
Your match arms both need to return the same type.您的比赛武器都需要返回相同的类型。 Since you want to request new input from the user, there's no need to handle the
Err
case here, just loop
until a correct value is entered.由于您想从用户那里请求新的输入,所以这里不需要处理
Err
情况,只需loop
直到输入正确的值。
This snippet loops until the value input
can be parsed without issues.该片段循环,直到可以毫无问题地解析值
input
。 In that case if let Some(v)..
it breaks with the value parsed.在这种情况下,
if let Some(v)..
它会破坏解析的值。 If the value cannot be parsed, it just loops along and tries again.如果无法解析该值,它只会循环并再次尝试。
let mut input = String::new();
let choice: u8 = loop {
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
println!("{}", input);
if let Some(v) = input.trim().parse().ok() {
break v;
}
input.clear();
println!("Invalid input. Please input a number.");
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.