简体   繁体   English

不匹配的类型需要 `i8`,发现 `()`

[英]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.

相关问题 不匹配的类型错误:预期的 `char`,找到参考 - Mismatched types error: expected `char`, found reference “不匹配的类型:预期的 `i16`,发现 `Result`”在猜数字游戏中 - "mismatched types: expected `i16`, found `Result`" in a number guessing game 返回的结构类型不匹配(预期 <K, V> ,找到&lt;&K,&V&gt;) - Mismatched types for returned struct (expected <K, V>, found <&K, &V>) 类型不匹配:在分配字符串时预期&str找到了字符串 - Mismatched types: expected &str found String when assigning string if let语句中的类型不匹配:找到期望结果 - Mismatched types in if let statement: found Option expected Result 错误类型不匹配:预期的&#39;collections :: vec :: Vec <i32> &#39;,找到了&#39;&collections :: vec :: Vec <i32> &#39; - Error mismatched types: expected 'collections::vec::Vec<i32>', found '&collections::vec::Vec<i32>' 错误[E0308]:预期类型不匹配 `()`,发现 `bool`。 如何消除此错误? - error[E0308]: mismatched types expected `()`, found `bool`. How to remove this error? 错误[E0308]:类型不匹配 - 预期结构 `Test`,发现 `&amp;Test` - error[E0308]: mismatched types - expected struct `Test`, found `&Test` 错误:类型不匹配:尝试实现冒泡排序时,出现了预期的&#39;usize&#39;,并出现了&#39;&usize&#39; - error: mismatched types: expected 'usize' found '&usize' raised while trying to implement bubble sort “不匹配的类型预期单元类型`()`找到枚举`选项<String> `&quot; 尝试使用 Tauri 读取文件内容时出错 - "mismatched types expected unit type `()` found enum `Option<String>`" Error when trying to read the content of a file with Tauri
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM