为什么Rust程序不从if语句返回值?

rob*_*yek 3 rust

我正在制作一个简单的控制台程序,可以在Celsius和Fahrenheit之间进行转换.该程序多次获取用户输入,一次用于转换类型,一次用于转换值.当我运行程序时,它编译并运行没有错误,但是,它实际上不返回任何值.

这是程序:

use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
    println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
    let mut convert_type = String::new();

    io::stdin()
        .read_line(&mut convert_type)
        .expect("Failed to conversion type.");

    let t = String::from(convert_type);

    println!("You want to convert to: {}", t);
    println!("What temperature would you like to convert?");
    let mut temp = String::new();

    io::stdin()
        .read_line(&mut temp)
        .expect("Failed to read temperature.");

    let temp: i32 = match temp.trim().parse() {
        Ok(temp) => temp,
        Err(_e) => -1,
    };

    if &t == "C" {
        println!("{}", ctof(temp));
    } else if &t == "F" {
        println!("{}", ftoc(temp));
    }
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
    (c * (9 / 5)) + 32
}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
    (f - 32) * (5 / 9)
}
Run Code Online (Sandbox Code Playgroud)

这是控制台的片段,因为您可以看到它不输出转换:

cargo run --verbose
   Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
     Running `rustc --crate-name ftoc src/main.rs --color always --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=8f02d379c2e5c97d -C extra-filename=-8f02d379c2e5c97d --out-dir /Users/roberthayek/rustprojects/ftoc/target/debug/deps -C incremental=/Users/roberthayek/rustprojects/ftoc/target/debug/incremental -L dependency=/Users/roberthayek/rustprojects/ftoc/target/debug/deps`
    Finished dev [unoptimized + debuginfo] target(s) in 1.16s
     Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
C
You want to convert to: C

What temperature would you like to convert?
0
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 12

你应养成处理所有案件的习惯,即使是你不期望的案件.如果你这样做了,你就会发现问题所在.所以不是这样的:

if &t == "C" {
    println!("{}", ctof(temp));
} else if &t == "F" {
    println!("{}", ftoc(temp));
}
Run Code Online (Sandbox Code Playgroud)

你可以写这个(你也可以使用if的最终else分支,但匹配更有吸引力):

match t.as_str() {
    "C" => println!("{}", ctof(temp)),
    "F" => println!("{}", ftoc(temp)),
    _ => println!("please enter C or F"),
}
Run Code Online (Sandbox Code Playgroud)

当你运行你的程序,你会看到t似乎是等于没有"C",也没有"F".希望t通过执行调试打印来引导您检查其值.

match t.as_str() {
    "C" => println!("{}", ctof(temp)),
    "F" => println!("{}", ftoc(temp)),
    _ => println!("t = {:?}", t),
}
Run Code Online (Sandbox Code Playgroud)

在这一点上你会看到值t不是"C",但是"C\n""C\r\n".然后你会意识到这read_line并没有从你的字符串中删除换行符.

  • 我似乎记得`无法到达!()`现在接受参数,所以你可能只能使用`unreachable!("t = {:?}",t"),`. (2认同)
  • 有趣.虽然我有点不假思索地编写了这段代码,但只是意识到`unreachable()`在这种情况下完全不合适,其中`t`来自用户输入. (2认同)