generic

Rust Generic enums

Use a type parameter when an enum variant carries data whose type depends on the caller. Delivery represents either an available payload or a waiting state. Expected output (not executed): Box waiting Why: The waiting variant does not carry a value to infer T from, so its annotation supplies the type. Common mistake: Assuming a payload-free variant always provides enough information to infer the type.

Formal Syntax & Structure

rust syntaxrust
enum Delivery<T> { Ready(T), Waiting }

Working Example

Example Snippetrust
enum Delivery<T> { Ready(T), Waiting }fn main() {    let order = Delivery::Ready("Box");    let waiting: Delivery<u32> = Delivery::Waiting;    if let Delivery::Ready(item) = order { println!("{item}"); }    if let Delivery::Waiting = waiting { println!("waiting"); }}
Rust Reference