It's one of the tasks suggested in the Rust Programming Language book by Steve Klabnik and Carol Nichols, and to a complete Rust newbie like me, figuring out converting scale from String
to Vec<char>
, was a bit of a challenge and a new concept, coming from Python.
I'd appreciate constructive criticism of what I've done wrong and right, pitfalls I may have fallen into, and possible optimizations available to be introduced to my code below.
use std::io;
fn main() {
println!("Please type `exit` to quit the program.");
loop {
println!("Please input source scale.\n`C` for Celsius, `F` for Fahrenheit.");
let mut scale = String::new();
io::stdin()
.read_line(&mut scale)
.expect("Failed to read input.");
if scale.trim() == "exit" {
break;
}
let scale = scale.trim().to_uppercase();
let scale: Vec<char> = scale.chars().collect();
let scale = scale[0];
let scale = match scale {
'C' => 'C',
'F' => 'F',
_ => {
println!("Incorrect scale.");
continue;
}
};
println!("Please input your source temperature with a trailing dot.");
let mut temperature = String::new();
io::stdin()
.read_line(&mut temperature)
.expect("Failed to read input.");
if temperature.trim() == "exit" {
break;
}
let temperature: f64 = match temperature.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please input a valid temperature.");
continue;
}
};
println!(
"Converted temperature is: {}.",
convert_temperature(scale, temperature)
);
}
}
fn convert_temperature(scale: char, temperature: f64) -> f64 {
let converted_temperature: f64 = if scale == 'F' {
(temperature as f64 - 32.0) / 1.8
} else {
temperature as f64 * 1.8 + 32.0
};
return converted_temperature;
}