Enums in Rust

Contents
Enums with data
Match them
Option is an enum
Result is an enum

Enums with data

An enum lists a fixed set of choices, and each choice can carry different data. This keeps related shapes in one type instead of loose flags plus extra structs.

Declare variants with struct style braces or tuple style parentheses, then build values with two colons and the variant name.

enum Message { Quit, Move { x: i32, y: i32 }, Write(String), } fn main() { let m = Message::Write(String::from("hi")); }

Message has three variants with three different shapes. The Write variant owns a String, so each message carries exactly the data its kind needs.

Match them

Match reads an enum value and runs the arm for its variant. Each arm names the variant and binds any data inside, so all handling stays in one place.

The compiler warns when an arm is missing, which keeps new variants from slipping through silently.

enum Coin { Penny, Nickel } fn value(c: Coin) -> u8 { match c { Coin::Penny => 1, Coin::Nickel => 5, } }

The value function turns each coin into cents. Add a third variant later and the compiler points at this match until every arm is complete.

Option is an enum

Option is an enum from the standard library with two variants, Some for a value and None for absence. It replaces null with a value the compiler forces handlers to check.

Build Some with a value inside and use None alone, then match or use helper methods to reach the inner value.

fn main() { let a: Option<i32> = Some(3); let b: Option<i32> = None; if a.is_some() { println!("yes"); } }

Here a holds a number and b holds nothing. The is_some check shows one way to ask which variant arrived before touching the value.

Result is an enum

Result is another standard library enum with Ok for success and Err for failure. Functions return it when an operation can fail with a message or an error value.

Callers match both arms, so success values and error values each get clear handling in the open.

fn check(n: i32) -> Result<i32, String> { if n >= 0 { Ok(n) } else { Err(String::from("negative")) } }

The check function accepts zero and positive numbers and rejects the rest. Ok carries the number forward while Err carries a short reason.

Next: Advanced match

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: