Enumerated types (enum, also called tagged unions) are ways to group together different values, often in a way that’s useful for selectors. They find broad support in almost every popular programming language (and SystemVerilog).

Enums help facilitate pattern matching.

In C/C++

In Rust

We can access the fields of an enum with enum::field. By default, all enum variants are public. We’re also able to embed the types inside an enum:

enum Message {
    Quit(Type), // where Type is another enum or struct
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

If we construct embedded variants Move, we need to:

let msg1 = Message::Move{x: 10, y: 20};
let msg2 = Message::ChangeColor(45, 10, -12);

Rust has no null value. The standard library does have the “option enum”, which functions similarly:

enum Option<T> {
	None,
	Some(T),
}

where T is a generic type. If a value takes on the None value, we must annotate it for the compiler.

Another important standard library enum is the result enum:

enum Result<T, Error> {
	Ok(T),
	Err(Error)
}