【问题标题】:Why is Rust program not returning values from if statements? [duplicate]为什么 Rust 程序不从 if 语句返回值? [复制]
【发布时间】:2019-04-12 15:13:47
【问题描述】:

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

这是程序:

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

这是控制台的一个sn-p,可以看到它没有输出转换:

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

【问题讨论】:

  • 您是否尝试过打印您的值以查看它的实际值?比如printl!("{?}", t);?
  • 以后请提供MCVE。您不需要发布您的完整程序,而是只有一起感兴趣的 sn-p 才会包含所有必需的功能和类型。请参阅rust-tag 了解有关 rust 特定 mcves 的更多信息,例如使用游乐场

标签: rust


【解决方案1】:

您应该养成处理所有情况的习惯,即使是您没有预料到的情况。如果你这样做了,你就会发现问题所在。所以不要这样:

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

你可以这样写(你也可以使用没有 if 的最终 else 分支,但是 match 更有吸引力):

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 并没有为您从字符串中删除换行符。

【讨论】:

  • 我好像记得unreachable!()现在接受参数,所以你也许可以只使用unreachable!("t = {:?}", t"),
  • 是的。查看unreachable!()的声明
  • 有趣。虽然我有点不假思索地写了这段代码,但我意识到unreachable()t 来自用户输入的情况下是完全不合适的。
  • 确实到达无法访问的代码是一个错误(在这种情况下是安全的,但仍然是一个错误)。
猜你喜欢
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多