Enums

Similarities between Enums and 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"));
  • The name of each enum variant that we define also becomes a function that constructs an instance of the enum.

    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
        ChangeColor(i32, i32, i32),
    }
    
    • Quit  has no data associated with it at all.

    • Move  has named fields, like a struct does.

    • Write  includes a single String .

    • ChangeColor  includes three i32  values.

  • We’re also able to define methods on enums using impl .

    impl Message {
        fn call(&self) {
            // method body
        }
    }
    
    let m = Message::Write(String::from("hello"));
    m.call();