73 lines
1.9 KiB
Rust
73 lines
1.9 KiB
Rust
|
use std::env;
|
||
|
use std::process;
|
||
|
|
||
|
fn main() {
|
||
|
let mut command = String::new();
|
||
|
let mut command_args = Vec::<String>::new();
|
||
|
for (i, arg) in env::args().enumerate() {
|
||
|
match i {
|
||
|
0 => continue,
|
||
|
1 => {
|
||
|
command = arg;
|
||
|
continue;
|
||
|
}
|
||
|
_ => command_args.push(arg.as_str().to_string()),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
match command.as_str() {
|
||
|
"tc" => {
|
||
|
if command_args.len() < 1 {
|
||
|
println!("ERROR: missing a value to convert");
|
||
|
process::exit(1);
|
||
|
}
|
||
|
temp_convert(command_args[0].as_str().to_string())
|
||
|
}
|
||
|
"rx" => redefine_x(),
|
||
|
"help" | _ => show_help(),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn show_help() {
|
||
|
println!("Usage: variables <command> [command_args]");
|
||
|
println!();
|
||
|
println!("The value for <command> may be one of:");
|
||
|
println!(" tc - convert temperatures between Fahrenheit and Celsius");
|
||
|
println!(" rx - redefine x");
|
||
|
println!();
|
||
|
}
|
||
|
|
||
|
fn redefine_x() {
|
||
|
let mut x = 5;
|
||
|
println!("The value of x is: {}", x);
|
||
|
x = 6;
|
||
|
println!("The value of x is: {}", x);
|
||
|
}
|
||
|
|
||
|
fn temp_convert(to_convert: String) {
|
||
|
let to_convert = to_convert.to_lowercase();
|
||
|
if to_convert.ends_with("c") {
|
||
|
let c: f32 = to_convert
|
||
|
.trim_end_matches('c')
|
||
|
.parse()
|
||
|
.expect("failed to parse temperature");
|
||
|
println!("{}F", temp_convert_c2f(c));
|
||
|
} else if to_convert.ends_with("f") {
|
||
|
let f: f32 = to_convert
|
||
|
.trim_end_matches('f')
|
||
|
.parse()
|
||
|
.expect("failed to parse temperature");
|
||
|
println!("{}C", temp_convert_f2c(f));
|
||
|
} else {
|
||
|
println!("What are we supposed to do to {:?}?", to_convert);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn temp_convert_c2f(c: f32) -> f32 {
|
||
|
(c * (9.0 / 5.0)) + 32.0
|
||
|
}
|
||
|
|
||
|
fn temp_convert_f2c(f: f32) -> f32 {
|
||
|
(f - 32.0) * (5.0 / 9.0)
|
||
|
}
|