Whenever I try a new language I always try to write a speed-distance-time calculator as well as possible. I did this with C++ a while ago now. This is a similar question but this time in Rust.
The program calculates speed, distance or time from the other two variables in the equation and the idea is to try to do this without a load of nested if statements and repetition. I try to make as elegant a solution as possible but the program needs to show the working for the equation.
I want to know how I could adjust the program to:
- Fit in with good (Rust) practices
- Shorten the program as much as possible
- Catch all errors
- Add support for units and conversions later on as well as other common equations
- Make better use of Rust
use std::io;
// Simple input function to simplify calc functions
fn get_param(s: &str) -> f64 {
println!("{}", s); // Print input instructions
loop { // loop until a float is entered
println!("Enter a floating point number!");
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("failed to read line");
let input: f64 = match input.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
return input;
}
}
fn calc_speed() -> f64 {
let distance: f64 = get_param("Enter distance:");
let time: f64 = get_param("Enter time:");
println!("Speed = distance / time");
println!("Speed = {} / {}", distance, time);
distance / time
}
fn calc_time() -> f64 {
let speed: f64 = get_param("Enter speed:");
let distance: f64 = get_param("Enter distance:");
println!("Time = distance / speed");
println!("Time = {} / {}", distance, speed);
distance / speed
}
fn calc_distance() -> f64 {
let speed: f64 = get_param("Enter speed:");
let time: f64 = get_param("Enter time:");
println!("Distance = speed * time");
println!("Distance = {} * {}", speed, time);
speed * time
}
fn main() {
let mut calc_input = String::new();
println!("Hello, would you like to calculate speed, distance or time?");
io::stdin().read_line(&mut calc_input)
.expect("failed to read line");
let answer: f64;
match calc_input.trim() {
"speed" | "Speed" => {
answer = calc_speed();
println!("Speed = {}", answer);
}
"distance" | "Distance" => {
answer = calc_distance();
println!("Distance = {}", answer);
}
"time" | "Time" => {
answer = calc_time();
println!("Time = {}", answer);
}
_ => {
println!("Enter speed, distance or time!")
}
}
}
I am new to Rust and know only a little about the language, coming primarily from C++. I know if I was writing C++ I would probably write a sdt class and maybe a struct for working.