working on enums. match and arms

This commit is contained in:
2026-10-06 20:56:33 +01:00
parent 96c444090d
commit 37a6496906
4 changed files with 106 additions and 1 deletions
+57
View File
@@ -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:#?}");
}
+5 -1
View File
@@ -1,3 +1,7 @@
mod defining_enums;
mod match_control_flow;
fn main() {
println!("Hello, world!");
defining_enums::run();
match_control_flow::run();
}
+40
View File
@@ -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
}
}
}