Generic enums let you create flexible types that can hold different kinds of data. This helps you reuse code and handle many situations with one design.
0
0
Generic enums in Rust
Introduction
When you want one enum to work with different data types without rewriting it.
When you need to store values of various types but keep them grouped in one enum.
When you want to write functions that work with enums holding any type.
When you want to create a container that can hold different types safely.
When you want to avoid repeating similar enums for each data type.
Syntax
Rust
enum EnumName<T> {
Variant1(T),
Variant2,
}The <T> after the enum name means it uses a generic type called T.
Each variant can use T to hold data of that generic type.
Examples
This enum can hold some value of any type or none at all.
Rust
enum Option<T> {
Some(T),
None,
}This enum holds either a success value
T or an error value E.Rust
enum Result<T, E> {
Ok(T),
Err(E),
}A simple container that can hold an item of any type or be empty.
Rust
enum Container<T> {
Item(T),
Empty,
}Sample Program
This program shows a generic enum Container holding different types: a number, a text, and an empty value. It prints each one using pattern matching.
Rust
enum Container<T> { Item(T), Empty, } fn main() { let number = Container::Item(42); let text = Container::Item("hello"); let empty: Container<i32> = Container::Empty; match number { Container::Item(value) => println!("Number: {}", value), Container::Empty => println!("No number"), } match text { Container::Item(value) => println!("Text: {}", value), Container::Empty => println!("No text"), } match empty { Container::Item(value) => println!("Empty has value: {}", value), Container::Empty => println!("Empty container"), } }
OutputSuccess
Important Notes
Generic enums help avoid writing many similar enums for different types.
You can use multiple generic types by adding more letters like <T, U>.
Pattern matching works the same way with generic enums.
Summary
Generic enums let you create flexible types that work with any data type.
They help reuse code and handle many cases with one enum.
Use pattern matching to get the data inside generic enums.