Rust Reference ยท Keywords and Statements
The enum keyword
Reference for Rust enum: unit, tuple and struct variants, matching on enums, explicit discriminants, casting, Option and Result, and enum memory size.
An enum is a type that is exactly one of several variants at a time. Unlike enums in C or Java, each variant can carry its own data: nothing (Quit), positional fields (Move(i32, i32)) or named fields (Write { text: String }). That makes an enum a sum type, the natural way to model "a value of one of these shapes".
You take an enum apart with match, which forces you to handle every variant. The standard library's Option<T> and Result<T, E> are ordinary enums; Rust has no null and no exceptions because enums cover those jobs.
enum Event { Quit, Move(i32, i32), Write { text: String }, }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
enum Name { Unit, Tuple(Type, Type), Struct { field: Type }, Explicit = 10, } enum Maybe<T> { Nothing, Just(T) } let v = Name::Tuple(1, 2);
| Part | Description |
|---|---|
| Variants | Always accessed with the enum name (Name::Unit) unless brought in with use Name::*;. |
| Discriminant | Variants without data may have = integer. Without #[repr], the integer type is chosen by the compiler; as casts are allowed for enums with only unit variants. |
#[repr(u8)] etc. |
Fixes the integer type of the discriminant, and the layout for data-carrying enums. |
| Generics | Enums can be generic, as in Option<T> and Result<T, E>. |
Errors: a missing variant in a match is E0004. Casting an enum that has data with as is E0605. There is no built-in conversion from integer to enum: write a TryFrom or a match.
Usage notes
- Size equals the largest variant plus a tag, minus tricks:
Option<Box<T>>andOption<&T>use the null pointer as the tag (the niche), so they are the same size as the pointer. - Derive the usual traits:
Debug,Clone,PartialEq, andCopywhere all fields allow it.Defaultneeds#[default]on one unit variant. - Recursive enums need indirection:
enum List { Cons(i32, Box<List>), Nil }. - Enum versus trait objects: an enum is closed (you know all variants, and
matchis checked), whiledyn Traitis open to new types. Prefer enums when the set is fixed. - Methods go in
implblocks; match onself,&selfor&mut self. #[non_exhaustive]on a public enum forces users in other crates to add a wildcard arm, so you can add variants without breaking them.- Matching a reference to an enum yields references to the fields; use
ref-free modern patterns and*only when you need copies. - Comparing variants:
==needsPartialEq; otherwise usematches!(x, Variant(..)).
Related
match,struct,Option<T>,Result<T, E>,matches!patterns- Lessons: Enums, Enums and match, Memory layout