Created
June 9, 2020 22:16
-
-
Save thomasdarimont/c93ce114f01ffdaa4c143933912de10f to your computer and use it in GitHub Desktop.
Rust experiments: Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::fmt; | |
use std::io::{self, Write}; | |
#[derive(Debug, Clone, Copy)] | |
enum BinaryOperator { | |
ADD, | |
SUB, | |
MUL, | |
DIV, | |
MOD, | |
} | |
impl BinaryOperator { | |
pub fn apply(self, a: i32, b: i32) -> i32 { | |
match self { | |
BinaryOperator::ADD => a + b, | |
BinaryOperator::SUB => a - b, | |
BinaryOperator::MUL => a * b, | |
BinaryOperator::DIV => a / b, | |
BinaryOperator::MOD => a % b | |
} | |
} | |
} | |
impl fmt::Display for BinaryOperator { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match *self { | |
BinaryOperator::ADD => write!(f, "+"), | |
BinaryOperator::SUB => write!(f, "-"), | |
BinaryOperator::MUL => write!(f, "*"), | |
BinaryOperator::DIV => write!(f, "/"), | |
BinaryOperator::MOD => write!(f, "%"), | |
} | |
} | |
} | |
fn read_input<T>(msg: &str, parse: impl Fn(&str) -> T) -> T { | |
print!("{}: ", msg); | |
io::stdout().flush().unwrap(); | |
let mut value = String::new(); | |
io::stdin().read_line(&mut value).expect("Failed to read"); | |
return parse(&value); | |
} | |
fn main() { | |
let first = read_input("First", |x: &str| x.trim().parse().ok().expect("Could not parse number")); | |
let second = read_input("Second", |x: &str| x.trim().parse().ok().expect("Could not parse number")); | |
let op = read_input("Operator", |x: &str| match x.trim() { | |
"+" => { BinaryOperator::ADD } | |
"-" => { BinaryOperator::SUB } | |
"*" => { BinaryOperator::MUL } | |
"/" => { BinaryOperator::DIV } | |
"%" => { BinaryOperator::MOD } | |
_ => { panic!(-1) } | |
}); | |
let result = op.apply(first, second); | |
println!("{} {} {} = {}", first, &op, second, result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment