diff --git a/Cargo.lock b/Cargo.lock index e96c7dd..efce0fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -24,6 +24,10 @@ version = "0.1.0" name = "common-programming-concepts-twelve-days-of-christmas" version = "0.1.0" +[[package]] +name = "enums" +version = "0.1.0" + [[package]] name = "getrandom" version = "0.2.17" diff --git a/enums/src/defining_enums.rs b/enums/src/defining_enums.rs new file mode 100644 index 0000000..33ca288 --- /dev/null +++ b/enums/src/defining_enums.rs @@ -0,0 +1,57 @@ +// For defining enums, we'll use ipv4 and ipv6. Ip addresses can only be one of these, so we put +// it in an enum block like this +#[derive(Debug)] +enum IpAddrKind { + V4, + V6, +} + + + +// One might try to use an enum and a struct to give it types, like this: +#[derive(Debug)] +struct IpAddr { + kind: IpAddrKind, + address: String, +} + +// this is however the most concise way +#[derive(Debug)] +enum IpAddrConcise { + V4(String), + V6(String), +} + + +pub fn run() { + println!("\n=== defining enums ===\n"); + route(IpAddrKind::V4); + route(IpAddrKind::V6); + + // building the structs + let home = IpAddr { + kind: IpAddrKind::V4, + address: String::from("127.0.0.1"), + }; + + let loopback = IpAddr { + kind: IpAddrKind::V6, + address: String::from("::1"), + }; + + // building with concise enum method + + println!("the home address is {home:#?}"); + println!("the loopback address is {loopback:#?}"); + + let home = IpAddrConcise::V4(String::from("127.0.0.1")); + let loopback = IpAddrConcise::V6(String::from("::1")); + + println!("the home address is {home:#?}"); + println!("the loopback address is {loopback:#?}"); + +} + +fn route (ip_kind: IpAddrKind) { + println!("your ip kind is {ip_kind:#?}"); +} diff --git a/enums/src/main.rs b/enums/src/main.rs index e7a11a9..809e182 100644 --- a/enums/src/main.rs +++ b/enums/src/main.rs @@ -1,3 +1,7 @@ +mod defining_enums; +mod match_control_flow; + fn main() { - println!("Hello, world!"); + defining_enums::run(); + match_control_flow::run(); } diff --git a/enums/src/match_control_flow.rs b/enums/src/match_control_flow.rs new file mode 100644 index 0000000..d41760f --- /dev/null +++ b/enums/src/match_control_flow.rs @@ -0,0 +1,40 @@ +use crate::match_control_flow::UsState::Alabama; + +#[derive(Debug)] +enum UsState { + Alabama, + Alaska +} + +// Her we define a basic enum +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +pub fn run() { + println!("\n=== match control flow ===\n"); + // + let penny = value_in_cents(Coin::Penny); + println!("The value of penny in cents is {penny}"); + + let alabama_quarter = value_in_cents(Coin::Quarter(Alabama)); + println!("the quarter is {alabama_quarter}"); +} + +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => { + println!("Lucky penny!"); + 1 + } + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter(state) => { + println!("State quarter from state {state:#?}"); + 25 + } + } +}