Kemel Zaidan
Kemel Zaidan

Reputation: 642

Why is my condition never met in Rust code?

I'm trying to learn Rust and in order to do that I created the exercise below to convert from Fahrenheit to Celsius and vice-versa.

use std::io;

fn show_options() {
    println!("You want to convert to:");
    println!("\t1. Celsius");
    println!("\t2. Fahrenheit");
    println!("Type your option number:");
}

fn print_invalid() {
    println!("Invalid option. Choose 1 or 2:\n")
}

fn main() {

    let result;
    let mut input = String::new();
    let mut temp = String::new();
    let input_num: u32 = 0;
    
    loop {
        input.clear();
        show_options();
        
        io::stdin()
            .read_line(&mut input)
            .expect("Failed to read line");
        
        
        let input_num: u32 = input.trim().parse().unwrap();
        match input_num {
            1 => break,
            2 => break,
            _ => {
                print_invalid();
                continue;
            },
        };
    };

    println!("What's the temperature?");
    
    io::stdin()
        .read_line(&mut temp)
        .expect("Failed to read line");

    let temp_num: f32 = temp.trim().parse().unwrap();

    // from F to C
    if input_num == 1 {
        result = (temp_num-32.0)*1.8;
        print!("The {temp_num}°F is {result}°C");
    // From C to F
    } else {
        result = (temp_num*1.8) + 32.0;
        print!("The {temp_num}°C is {result}°F");
    };
}

The problem is that the first condition on the last if is never met and I can't understand why. Using a debugger, I can see that the input_num variable switches its value from the value chosen by the user input (let's say 1) to 0 and I can't understand why.

I'd be glad if a more experienced Rust programmer can tell me what is happening with my code.

Upvotes: 1

Views: 67

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71430

You have two input_nums.

Outside the loop, you declared let input_num = 0;. This is the input_num for the code outside the loop, and it is always zero.

Inside it, you have another one, let input_num: u32 = input.trim().parse().unwrap();. In each iteration of the loop it is created, the vanishes: it does not exist outside of the loop. This variable shadows the first input_num.

A suspicious sign is that you didn't declare the first input_num as mut, which means it is not mutable. So, it will always stay with its initial value, zero.

Since you're accessing input_num outside of the loop, you're accessing the first one, which is always zero.

Instead, mark the first input_num as mut, and remove the let from the second input_num to make it an assignment and not a declaration.

Upvotes: 4

Related Questions