Created
November 16, 2021 23:46
-
-
Save ulisesantana/d0f67731e795a21b6ca35fc0a6e7eb71 to your computer and use it in GitHub Desktop.
Ejemplo de tipos algebraicos en Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub mod flight_discount { | |
pub trait Discount { | |
fn percentage(self: Self) -> u8; | |
} | |
#[allow(dead_code)] | |
pub enum SpanishSubsidy { | |
LargeFamily, | |
ResidentOfIslandsOrCeuta, | |
SpecialResidentLargeFamily, | |
None, | |
} | |
impl Discount for SpanishSubsidy { | |
fn percentage(self: Self) -> u8 { | |
match self { | |
SpanishSubsidy::LargeFamily => 10, | |
SpanishSubsidy::ResidentOfIslandsOrCeuta => 75, | |
SpanishSubsidy::SpecialResidentLargeFamily => 85, | |
_ => 0 | |
} | |
} | |
} | |
#[allow(dead_code)] | |
pub enum FlightDiscount { | |
Business, | |
SubsidyPlusBusiness, | |
NoDiscount, | |
} | |
impl Discount for FlightDiscount { | |
fn percentage(self) -> u8 { | |
match self { | |
FlightDiscount::Business => 5, | |
FlightDiscount::SubsidyPlusBusiness => { | |
SpanishSubsidy::ResidentOfIslandsOrCeuta.percentage() + | |
FlightDiscount::Business.percentage() | |
} | |
FlightDiscount::NoDiscount => 0 | |
} | |
} | |
} | |
pub fn calculate_discount_percentage<T: Discount>(discount: T) -> u8 { | |
discount.percentage() | |
} | |
} | |
#[cfg(test)] | |
mod flight_discount_tests { | |
use crate::flight_discount::{calculate_discount_percentage, SpanishSubsidy, FlightDiscount}; | |
// Spanish subsidy tests | |
#[test] | |
fn spanish_subsidy_for_large_family_is_10() { | |
assert_eq!( | |
calculate_discount_percentage(SpanishSubsidy::LargeFamily), | |
10 | |
); | |
} | |
#[test] | |
fn spanish_subsidy_for_residents_of_islands_or_ceuta_is_75() { | |
assert_eq!( | |
calculate_discount_percentage(SpanishSubsidy::ResidentOfIslandsOrCeuta), | |
75 | |
); | |
} | |
#[test] | |
fn spanish_subsidy_for_large_family_residents_of_islands_or_ceuta_is_85() { | |
assert_eq!( | |
calculate_discount_percentage(SpanishSubsidy::SpecialResidentLargeFamily), | |
85 | |
); | |
} | |
#[test] | |
fn default_spanish_subsidy_is_zero() { | |
assert_eq!( | |
calculate_discount_percentage(SpanishSubsidy::None), | |
0 | |
); | |
} | |
// Flight discount tests | |
#[test] | |
fn flight_discount_for_business_is_5() { | |
assert_eq!( | |
calculate_discount_percentage(FlightDiscount::Business), | |
5 | |
); | |
} | |
#[test] | |
fn flight_discount_for_subsidy_plus_business_is_80() { | |
assert_eq!( | |
calculate_discount_percentage(FlightDiscount::SubsidyPlusBusiness), | |
80 | |
); | |
} | |
#[test] | |
fn flight_discount_with_no_discount_is_zero() { | |
assert_eq!( | |
calculate_discount_percentage(FlightDiscount::NoDiscount), | |
0 | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment