liveBook · Manning

Enum

As explained in Code Like a Pro in Rust

An enum is a Rust type that represents a value selected from a defined set of variants, which may carry associated data.

An enum models a value selected from mutually exclusive variants. Unlike a struct, which contains all its fields, an enum contains only its active variant. Variants may be unit-like, tuple-like, struct-like, or carry named or anonymous types. section 4.5.4

Use enums to:

  • Represent a closed set of named choices, including C-like values with explicit discriminants. section 4.5.4
  • Attach data directly to each choice through tuple, struct, or anonymous variant types. section 4.5.4
  • Add debugging output with derived traits such as Debug, or implement conversions manually when automatic conversion is unavailable. section 4.5.4 section 4.9
enum EnumTypes {
    NamedType,                     #1
    String,                        #2
    NamedString(String),           #3
    StructLike { name: String },   #4
    TupleLike(String, i32),        #5
}

Compare unit-like, named-data, tuple-like, and struct-like variants in one compact declaration. section 4.5.4

Conversion and discriminants

A C-like enum can be cast to u32 for comparison or output when its variants are enumerated. The reverse conversion is not automatic: implement From<u32> manually, match every known discriminant, and decide how unknown values should be handled. The demonstrated implementation panics for an unknown value, so production code should treat that failure policy as an explicit design choice. section 4.5.4

Prefer data-carrying variants when the choice and its payload belong together. Derive standard traits where sufficient, and avoid assuming that an enum's numeric discriminant provides a general-purpose serialization or conversion contract. section 4.5.4 section 4.9

How Code Like a Pro in Rust covers it

How deep it goes
Defines variant forms, discriminant casts, and manual numeric conversion, but does not develop broader enum control-flow patterns.
Examples
Uses Japanese dog breeds, explicit numeric variants, Debug output, From<u32>, and mixed named, tuple, and struct-like variants.
What it assumes
Assumes basic Rust syntax and familiarity with primitive types and structs while positioning enums among Rust's core type categories.
What you can do after
Build it from scratch as a Rust enum, attach heterogeneous variant data, derive traits, cast discriminants, and implement numeric conversion.
How it connects
Connects enums with structs, primitive types, traits, type aliases, and numeric conversion.

Also explained in

Compare how 23 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.