#[derive(Debug, PartialEq)]
pub enum Unit {
Celsius,
Fahrenheit,
Kelvin,
}
#[derive(Debug)]
pub struct Temperature {
value: f64,
unit: Unit,
}
impl Temperature {
pub fn new(value:f64, unit: Unit) -> Option<Self> {
let valid_temp = match unit {
Unit::Celsius => value >= -273.15,
Unit::Fahrenheit => value >= -459.67,
Unit::Kelvin => value >= 0.0,
};
if valid_temp {
Some(Self { value, unit })
} else {
None
}
}
pub fn get_value(&self) -> f64 {
self.value
}
pub fn to_celsius(&self) -> Option<Self> {
let celsius = match self.unit {
Unit::Celsius => self.value,
Unit::Fahrenheit => (self.value - 32.0) * 5.0 / 9.0,
Unit::Kelvin => self.value - 273.15,
};
Self::new(celsius, Unit::Celsius)
}
pub fn to_fahrenheit(&self) -> Option<Self> {
let fahrenheit = match self.unit {
Unit::Fahrenheit => self.value,
Unit::Celsius => (self.value * 9.0 / 5.0) + 32.0,
Unit::Kelvin => (self.value - 273.15) * 9.0 / 5.0 + 32.0,
};
Self::new(fahrenheit, Unit::Fahrenheit)
}
pub fn to_kelvin(&self) -> Option<Self> {
let kelvin = match self.unit {
Unit::Kelvin => self.value,
Unit::Celsius => self.value + 273.15,
Unit::Fahrenheit => (self.value - 32.0) * 5.0 / 9.0 + 273.15,
};
Self::new(kelvin, Unit::Kelvin)
}
}