From 4d448d3ba4df1b16d2bea9e4fc28095fdcd1c0bd Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Thu, 19 Jan 2023 15:48:41 -0330 Subject: add convert() method to Volume trait --- src/volume.rs | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index feeae14..675dfaa 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -9,15 +9,17 @@ pub trait Volume { fn set(&mut self, val: f64); - fn unit(&self) -> VolumeUnit; + fn unit(&self) -> Unit; + + fn convert(self, unit: Unit) -> Box; } -pub enum VolumeUnit { +pub enum Unit { CubicMetre, Litre, } -impl Display for VolumeUnit { +impl Display for Unit { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, @@ -42,8 +44,21 @@ impl Volume for CubicMetre { self.0 = val; } - fn unit(&self) -> VolumeUnit { - VolumeUnit::CubicMetre + fn unit(&self) -> Unit { + Unit::CubicMetre + } + + fn convert(self, unit: Unit) -> Box { + match unit { + Unit::CubicMetre => Box::new(self), + Unit::Litre => Box::new(Litre::from(self)), + } + } +} + +impl From for CubicMetre { + fn from(value: Litre) -> Self { + value.si() } } @@ -59,8 +74,15 @@ impl Volume for Litre { self.0 = val } - fn unit(&self) -> VolumeUnit { - VolumeUnit::Litre + fn unit(&self) -> Unit { + Unit::Litre + } + + fn convert(self, unit: Unit) -> Box { + match unit { + Unit::CubicMetre => Box::new(CubicMetre::from(self)), + Unit::Litre => Box::new(self), + } } } -- cgit v1.2.3