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

时间:2018-11-09 02:47:45

标签: rust

我正在制作一个简单的控制台程序,可以在摄氏温度和华氏温度之间转换。该程序多次接受用户输入,一次输入转换类型,一次输入转换值。当我运行程序时,它会编译并没有错误地运行,但是,它实际上并没有返回任何值。

这是程序:

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)
}

以下是控制台的摘要,如您所见,它不输出转换:

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

1 个答案:

答案 0 :(得分:12)

您应该养成处理所有案件的习惯,即使您没有想到。如果这样做,您将发现问题。所以代替这个:

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

您可以这样写(您也可以使用没有if的final else分支,但匹配更具吸引力):

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

运行程序时,您会发现t似乎既不等于"C"也不等于"F"。希望可以通过调试打印来检查t的值。

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

此时,您会看到t的值不是"C",而是"C\n""C\r\n"。然后您会意识到read_line并没有为您剥离字符串中的换行符。