I am learning Rust. I am following the book second edition, and I was doing the exercises given at the end of this chapter.
I did Convert temperatures between Fahrenheit and Celsius. The code is:
use std::io;
fn main() {
println!("Welcome to temperature conversion tool.");
println!("---------------------------------------");
loop {
let mut choice = String::new();
println!("1. Fahrenheit to Celsius");
println!("2. Celsius to Fahrenheit");
println!("0. Quit");
println!("Enter your choice");
io::stdin().read_line(&mut choice)
.expect("Failed to read input");
let choice: u32 = match choice.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
if choice == 1 {
let mut temperature = String::new();
println!("Enter Fahrenheit temperature");
io::stdin().read_line(&mut temperature)
.expect("Failed to read input");
let temperature: f32 = match temperature.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("Celsius temperature is {}", fahrenheit_to_celsius(temperature));
} else if choice == 2 {
let mut temperature = String::new();
println!("Enter Celsius temperature");
io::stdin().read_line(&mut temperature)
.expect("Failed to read input");
let temperature: f32 = match temperature.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("Fahrenheit temperature is {}", celsius_to_fahrenheit(temperature));
} else if choice == 0 {
break;
} else {
println!("Invalid choice");
continue;
}
}
}
fn fahrenheit_to_celsius(x: f32) -> f32 {
(x - 32.0) * (5.0 / 9.0)
}
fn celsius_to_fahrenheit(x: f32) -> f32 {
x * 9.0 / 5.0 + 32.0
}
You can see that inside the loop
and if
condition I am creating mutable variables.
I would like to know how it impacts the system I am running this program on. For example,
- Does it allocates a new placeholder in the system memory for the new variable? Everytime a new variable is declared?
Thank you.