index : temp_converter
Convert temperature degres
about summary refs log tree commit diff
temp_converter / src / main.rs
-rw-r--r-- blob 8cc789e7988b442fa993b12257532df0e7783cfe 2546 bytes (plain)
1
use std::{
2
    fmt::Display,
3
    io,
4
};
5
6
struct Fahrenheit(f64);
7
struct Celsius(f64);
8
9
enum Convert {
10
    FahrenheitToCelsius(Fahrenheit),
11
    CelsiusToFahrenheit(Celsius),
12
}
13
14
impl Display for Convert {
15
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16
        match self {
17
            Convert::FahrenheitToCelsius(fahrenheit) => {
18
                write!(f, "{fahrenheit} is equal to {}", Celsius::from(fahrenheit))
19
            }
20
            Convert::CelsiusToFahrenheit(celsius) => {
21
                write!(f, "{celsius} is equal to {}", Fahrenheit::from(celsius))
22
            }
23
        }
24
    }
25
}
26
27
const RED: &str = "\x1b[0;31m";
28
const YELLOW: &str = "\x1b[0;33m";
29
const BLUE: &str = "\x1b[0;34m";
30
const RESET: &str = "\x1b[0m";
31
fn main() {
32
    println!("Welcome to the temperature converter!");
33
34
    loop {
35
        println!("Which way do you need to convert?");
36
        println!("{BLUE}Fahrenheit{RESET} {YELLOW}--->{RESET} {RED}Celsius: Press 1{RESET}");
37
        println!("{RED}Celsius{RESET} {YELLOW}--->{RESET} {BLUE}Fahrenheit: Press 2{RESET}");
38
        println!("(Press q to quit)");
39
40
        let mut direction = String::new();
41
        io::stdin()
42
            .read_line(&mut direction)
43
            .expect("Failed to read line.");
44
45
        let direction = direction.trim();
46
47
        let result = match direction {
48
            "q" | "Q" => break,
49
            "1" => Convert::FahrenheitToCelsius(Fahrenheit(read_temp())),
50
            "2" => Convert::CelsiusToFahrenheit(Celsius(read_temp())),
51
            _ => {
52
                println!("Please make a valid selection!");
53
                continue;
54
            }
55
        };
56
57
        println!("{result}")
58
    }
59
}
60
61
fn read_temp() -> f64 {
62
    println!("What is starting temperature?");
63
    let mut temp = String::new();
64
    io::stdin()
65
        .read_line(&mut temp)
66
        .expect("Failed to read line.");
67
    let parsed_temp: f64 = temp.trim().parse().expect("Please type a number!");
68
    parsed_temp
69
}
70
71
impl From<&Fahrenheit> for Celsius {
72
    fn from(fahrenheit: &Fahrenheit) -> Self {
73
        Celsius((fahrenheit.0 - 32.0) * 0.555555556)
74
    }
75
}
76
77
impl Display for Celsius {
78
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79
        write!(f, "{}C", self.0)
80
    }
81
}
82
83
impl From<&Celsius> for Fahrenheit {
84
    fn from(celsius: &Celsius) -> Self {
85
        Fahrenheit((celsius.0 * 1.8) + 32.0)
86
    }
87
}
88
89
impl Display for Fahrenheit {
90
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91
        write!(f, "{}F", self.0)
92
    }
93
}