SHARE
TWEET

Untitled

a guest Sep 24th, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //1: create an inventory item
  2. //2: output the converted value
  3. //3: Use a trait
  4.  
  5. // 1 kilogram = 2.20462262184878 pounds
  6. // pounds = 2.2 * kilograms
  7.  
  8. pub const KILOGRAM_FACTOR: f64 = 1.0;
  9. pub const KILOGRAM_TONNE_FACTOR: f64 = 14.0;
  10. pub const KILOGRAM_POUND_FACTOR: f64 = 2.20462262184878;
  11. pub const KILOGRAM_STONE_FACTOR: f64 = 0.157473;
  12.  
  13. enum UomWeight { Kilos, Pounds, Stone }
  14. struct InventoryItem { weight: f64, uom: UomWeight }
  15.  
  16. pub trait MeasurementConverter {
  17.     fn to_pounds(&self) -> f64;
  18.     fn to_kilos(&self) -> f64;
  19.     fn to_stone(&self) -> f64;
  20. }
  21.  
  22. impl MeasurementConverter for InventoryItem {
  23.     fn to_pounds(&self) -> f64 {
  24.         match self.uom {
  25.             UomWeight::Pounds => self.weight, UomWeight::Kilos => self.weight * KILOGRAM_POUND_FACTOR,
  26.             UomWeight::Stone => self.weight * KILOGRAM_TONNE_FACTOR
  27.         }
  28.     }  
  29.  
  30.     fn to_kilos(&self) -> f64 {
  31.         match self.uom {
  32.             UomWeight::Kilos => self.weight, UomWeight::Pounds => self.weight / KILOGRAM_POUND_FACTOR,
  33.             UomWeight::Stone => self.weight / KILOGRAM_STONE_FACTOR
  34.         }
  35.     }
  36.  
  37.     fn to_stone(&self) -> f64 {
  38.         match self.uom {
  39.             UomWeight::Stone => self.weight, UomWeight::Pounds => self.weight / KILOGRAM_TONNE_FACTOR,
  40.             UomWeight::Kilos => self.weight * KILOGRAM_STONE_FACTOR
  41.         }
  42.     }  
  43. }
  44.  
  45. pub fn print_table_header() {    
  46.     println!("\n{0: <30} | {1: <30} | {2: <30}","Pounds", "Kilos", "Stone");
  47. }
  48.  
  49. pub fn display_convert<T>(mass: T) where T: MeasurementConverter {                    
  50.     println!("{0: <30} | {1: <30} | {2: <30} ", mass.to_pounds(), mass.to_kilos(), mass.to_stone());    
  51. }
  52.  
  53. fn main() {    
  54.     print_table_header();
  55.     display_convert(InventoryItem {weight: KILOGRAM_FACTOR, uom: UomWeight::Pounds});
  56.     display_convert(InventoryItem {weight: KILOGRAM_FACTOR, uom: UomWeight::Kilos});
  57.     display_convert(InventoryItem {weight: KILOGRAM_FACTOR, uom: UomWeight::Stone});    
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top