Rust - Basic - 06 - Enum

Enum

Comprehension

  • Basic syntax

    // basic declaration
    enum IpAddrKind {
        V4,
        V6,
    }
    // basic usage
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;
    
    // can be used in a struct
    struct IpAddr {
        kind: IpAddrKind,
        address: String,
    }
    
    // can contain different types, including structs
    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 Ipv4Addr {
        // --snip--
    }
    struct Ipv6Addr {
        // --snip--
    }
    enum IpAddr {
        V4(Ipv4Addr),
        V6(Ipv6Addr),
    }
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
        ChangeColor(i32, i32, i32),
    }
    
    // like structs, enums support impl blocks
    impl Message {
        fn call(&self) {
            // method body would be defined here
        }
    }
    
  • Combining with match

    match must cover every possible enum value

    If you do not list every possible enum value, use another variable or an underscore

    All values returned by a match expression must have the same type

    Note that match can also trigger a move

    Other uses of match are described in later chapters

    #[derive(Debug)]
    enum UsState {
        Alabama,
        Alaska,
        // --snip--
    }
    #[derive(Debug)]
    enum Coin {
        Penny,
        Nickel,
        Dime,
        Quarter(UsState),
    }
    fn value_in_cents(coin: Coin) -> u8 {
        match coin {
            Coin::Penny => 1,  // braces can be omitted for a single line
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter(state) => {
    					// this value may be UsState::Alabama or UsState::Alaska
                println!("State quarter from {:?}!", state);
                25
            }
        };
        match coin {
            Coin::Penny => 1,
    			// use another variable to represent other cases
            a => {
                println!("{:?}", a);
                5
            },
        };
        match coin {
            Coin::Penny => 1,
    			// use an underscore
            _ => 5,
        }
    }
    
  • Combining with if let

    let mut count = 0;
    
    // `match` version
    match coin {
        Coin::Quarter(state) => println!("State quarter from {:?}!", state),
        _ => count += 1,
    }
    
    // `if let` version
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }
    

Origin

https://doc.rust-lang.org/book/ch06-00-enums.html