C8: Enums and Pattern Matching Flashcards

1
Q

Basic Enum

A
enum IpAddrKind {
        V4,
        V6,
    }

    enum IpAddr {
        V4(u8, u8, u8, u8),
        V6(String),
    }

    let home = IpAddr::V4(127, 0, 0, 1);

    let loopback = IpAddr::V6(String::from("::1"));

    struct IpAddr {
        kind: IpAddrKind,
        address: String,
    }

    let home = IpAddr {
        kind: IpAddrKind::V4,
        address: String::from("127.0.0.1"),
    };

    let loopback = IpAddr {
        kind: IpAddrKind::V6,
        address: String::from("::1"),
    };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

The Option Enum and Its Advantages Over Null Values

A

This section explores a case study of Option, which is another enum defined by the standard library. The Option type encodes the very common scenario in which a value could be something or it could be nothing.

enum Option<T> {
    None,
    Some(T),
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The Pattern Match Basic Control Flow Construct

A
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Pattern Matching That Bind to Values

A
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {:?}!", state);
            25
        }
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Pattern Matching with Option<T></T>

A
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Patterns Matches Are Exhaustive?

A

YES. The arms’ patterns must cover all possibilities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Catch-all Patterns and the _ Placeholder

A

let dice_roll = 9;
match dice_roll {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
_ => (),
}

fn add_fancy_hat() {}
fn remove_fancy_hat() {}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly