Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. fn main() {
  2. let usa = Country {
  3. name: "USA",
  4. taxer: Box::new(CompoundTaxer {
  5. base: SimpleTaxer {
  6. rate: 2.3,
  7. },
  8. compound_rate: 3.3,
  9. }),
  10. };
  11.  
  12. println!("{}", usa.taxer.calculate_tax(333.0));
  13. }
  14.  
  15. struct Country {
  16. pub name: &'static str,
  17. pub taxer: Box<dyn Taxer>,
  18. }
  19.  
  20. trait Taxer {
  21. fn calculate_tax(&self, amount: f32) -> f32;
  22. }
  23.  
  24. struct SimpleTaxer {
  25. rate: f32,
  26. }
  27.  
  28. impl Taxer for SimpleTaxer {
  29. fn calculate_tax(&self, amount: f32) -> f32 {
  30. amount * self.rate
  31. }
  32. }
  33.  
  34. struct CompoundTaxer {
  35. base: SimpleTaxer,
  36. compound_rate: f32,
  37. }
  38.  
  39. impl Taxer for CompoundTaxer {
  40. fn calculate_tax(&self, amount: f32) -> f32 {
  41. let base_tax = &self.base.calculate_tax(amount);
  42. base_tax + amount * self.compound_rate
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement