Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enum

Enums definition

  • A value can be one of a possible set of values (variant)
  • All variants have the same custom data type
// enum definition
enum IpAddrKind {
    V4,
    V6,
}

Enum values

  • Single function can take any variant as a parameter due to their common data type.
// instantiating enum
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
// fn taking any variant as a parameter
fn route(ip_kind: IppAddrKind) {}

// function call
route(IpAddrKind::V4);
route(IpAddrKind::V6);

Enum associated data

  • Each enum variant can have different types and amounts of associated data
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

Methods

  • Similarly to struct we can define methods on enum by using impl
    impl Message {
        fn call(&self) {
            // method body would be defined here
        }
    }

    let m = Message::Write(String::from("hello"));
    m.call();

The option enum

  • Enum to encode the concept of a value being present or absent. Value is either
    • sone(value) - it exist or
    • none - it does not exist
  • Part of the standard library and included in the prelude (no need to bring it into scope explicitly)
  • Type annotation:
    • some(value) - data type can be inferred
    • none - type annotation must be explicit
enum Option<T> {
    None,
    Some(T),
}

Practicle example:

fn safe_divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 {
        None
    } else {
        Some(a / b)
    }
}

fn main() {
    let result = safe_divide(10, 2);

    match result {
        Some(value) => println!("Result: {}", value),
        None => println!("Cannot divide by zero"),
    }
}