enum

A versatile tool used to represent a type that can take on one of several possible variants. Allows variants to hold different kinds and amounts of data.

Syntax:

enum name {
	type1,
	type2
}

let x = name::type1

These could be assign by structs, but can also be assigned type directly in the enum. Enums can contain any type, strings, numeric types, structs, even other enums.

Example Enum

enum IpAddrKind {
        V4,
        V6
}

let _four = IpAddrKind::V4;
let _six = IpAddrKind::V6;

fn route(_ip_kind: IpAddrKind) {}

routeV4;
routeV6;

Example assigning type via enum

Each variant can have different types and amounts of associated data.

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

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

IpAddr::V4() is a function call that takes a String argument and returns an instance of the IpAddr type. We automatically get this constructor function defined as a result of defining the enum.

Example with multiple types

enum Message { 
	Quit, 
	Move { x: i32, y: i32 }, 
	Write(String), 
	ChangeColor(i32, i32, i32), 
}

Option
enum Option<T>

Example error handling with Option

fn divide(numerator: f64, denominator: f64) -> Option<f64> {
    if denominator == 0.0 {
        None
    } else {
        Some(numerator / denominator)
    }
}

fn main() {
  
let result = divide(10.0, 2.2);
match result{
    Some(x) => println!{"Result: {}", x},
    None => println!{"Cannot divide by Zero!"},
}
}

Example error handling with Result

fn divideResult(numerator: f64, denominator: f64) -> Result<f64, String> {
    if denominator == 0.0 {
        Err("Cannot divide by 0".to_string())
    } else {
        Ok(numerator / denominator)
    }
}

match divideResult(100.23, 0.0){
    Ok(result) => println!{"Result: {}", result},
    Err(err) => println!{"Error: {}", err},
}