Learning rust - Convert temperatures between Fahrenheit and Celsius
28/02/2018
I've just started going through the Rust-lang tutorial and I guess it is the first of many posts about learning rust (or maybe not).
My takeaways so far:
- if statements doesn't have parentehesises as in Go
- cargo is pretty neat tool
- when reading input from STDIN, don't forget to trim single trailing newline.
And as tutorial suggests, I've written temperature converter from Fahrenheit and Celsius and other way around:
use std::io;
use std::string::String;
fn main() {
println!("Please, choose conversion type:");
println!("[1] Fahrenheit to Celsius");
println!("[2] Celsius to Fahrenheit");
let mut option = String::new();
io::stdin()
.read_line(&mut option)
.expect("Failed to read line");
// trim single trailing newline.
option.pop();
if option != "1" && option != "2" {
println!("Wrong input, please select 1 or 2.");
return
}
println!("Please, type tempereture.");
let mut tmp = String::new();
io::stdin()
.read_line(&mut tmp)
.expect("Failed to read line");
let tmp: i32 = match tmp.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Can't parse input.");
return
},
};
if option == "1" {
to_celsius(tmp);
} else if option == "2" {
to_fahrenheit(tmp);
}
}
fn to_celsius(f :i32) {
println!("{} C", (f - 32)*5/9);
}
fn to_fahrenheit(c :i32) {
println!("{} F", c*9/5+32);
}