Last active
March 1, 2018 17:51
-
-
Save dangets/8bce6f2dab30a06df5518621d8725e27 to your computer and use it in GitHub Desktop.
domain-modeling-made-functional rust and/or types
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
// OR types | |
#[derive(Debug, Copy, Clone, PartialEq)] | |
enum AppleVariety { | |
GoldenDelicious, | |
GrannySmith, | |
Fuji | |
} | |
#[derive(Debug, Copy, Clone, PartialEq)] | |
enum BananaVariety { | |
Cavendish, | |
GrosMichel, | |
Manzano | |
} | |
#[derive(Debug, Copy, Clone, PartialEq)] | |
enum CherryVariety { | |
Montmorency, | |
Bing | |
} | |
// AND type | |
#[derive(Debug, Copy, Clone, PartialEq)] | |
struct FruitSalad { | |
apple: AppleVariety, | |
banana: BananaVariety, | |
cherry: CherryVariety | |
} | |
#[derive(Debug, PartialEq)] | |
enum Snack { | |
FruitSalad(FruitSalad), | |
HandfulOfNuts { name: String, count: u8 } | |
} | |
fn offer_snack(snack: Snack) { | |
match snack { | |
Snack::FruitSalad(FruitSalad { apple: AppleVariety::GrannySmith, .. }) => | |
println!("I don't like granny smith apples"), | |
Snack::FruitSalad(fs) => | |
println!("YAY fruit salad {:?}", fs), | |
Snack::HandfulOfNuts { name, count } => | |
println!("Ah just {:?} {}?", count, name) | |
} | |
} | |
fn main() { | |
let fs = FruitSalad { | |
apple: AppleVariety::GoldenDelicious, | |
banana: BananaVariety::Cavendish, | |
cherry: CherryVariety::Montmorency | |
}; | |
let nuts = Snack::HandfulOfNuts { name: "almonds".to_string(), count: 20 }; | |
let fs_granny = FruitSalad { apple: AppleVariety::GrannySmith, .. fs }; | |
offer_snack(Snack::FruitSalad(fs)); | |
offer_snack(nuts); | |
offer_snack(Snack::FruitSalad(fs_granny)); | |
//println!("{:?}", fs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment