RRust By Example
intermediateGenerics

Generic Enums

Standard library generic enums like Option and Result.

Generic Enums

Standard library generic enums like Option and Result.

Difficulty

Intermediate

Code

rust
// Define a generic enum similar to Option
enum Maybe<T> {
    Just(T),
    Nothing,
}

impl<T> Maybe<T> {
    fn is_some(&self) -> bool {
        match self {
            Maybe::Just(_) => true,
            Maybe::Nothing => false,
        }
    }

    fn unwrap(self) -> T {
        match self {
            Maybe::Just(v) => v,
            Maybe::Nothing => panic!("unwrap on Nothing"),
        }
    }
}

fn main() {
    let x: Maybe<i32> = Maybe::Just(42);
    let y: Maybe<i32> = Maybe::Nothing;

    println!("x is some: {}", x.is_some());
    println!("y is some: {}", y.is_some());
    println!("x = {}", x.unwrap());
}

Explanation

Standard enums like Option are generic.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the generics category to build a complete understanding of this topic.

More Generics Examples