Giving data a shape
So far, every value has been a number, a string, or a tuple of them. Real programs deal in books and payments, cities and timetables, and they need to say so. Rust gives you two ways to define your own types, and between them they cover almost everything:
- A struct says "a value of this type has all of these parts": a book has a title and an author and a year.
- An enum says "a value of this type is one of these alternatives": a payment is cash or a card or mobile money, and each alternative carries its own data.
Mathematicians call these product types and sum types. Many popular languages have the first in some form (classes, records) but only a weak version of the second, usually a list of named integers. Rust's enums are full sum types, and combined with match they let you write code that the compiler checks for forgotten cases.
Two enums from the standard library, Option and Result, are so central that they change how Rust programs handle missing values and errors. There is no null in safe Rust and no exceptions. Instead, "this might be absent" and "this might fail" are written into the types, where neither the compiler nor the next person reading your code can miss them. A phrase you will hear often in Rust circles sums up the goal of this lesson: make illegal states unrepresentable.
Structs and methods
Definition— struct
A struct groups named fields into a new type: struct Book { title: String, year: u16 }. A tuple struct has unnamed fields accessed by position: struct Celsius(f64);. A struct with one field used to give a plain value a distinct meaning is called a newtype. Methods and associated functions are defined separately, in an impl block for the type.
#[derive(Debug, Clone, PartialEq)]
struct Book {
title: String,
author: String,
year: u16,
on_loan: bool,
}
impl Book {
// An associated function (no `self`): the conventional constructor.
fn new(title: &str, author: &str, year: u16) -> Self {
Self {
title: title.to_string(),
author: author.to_string(),
year,
on_loan: false,
}
}
// A method that reads the book.
fn label(&self) -> String {
format!("{} by {} ({})", self.title, self.author, self.year)
}
// A method that changes the book; it needs `&mut self`.
fn lend(&mut self) -> bool {
if self.on_loan {
false
} else {
self.on_loan = true;
true
}
}
}
// A tuple struct with one field: a "newtype" that gives a number a meaning.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Celsius(f64);
fn main() {
let mut book = Book::new("Things Fall Apart", "Chinua Achebe", 1958);
println!("{}", book.label());
println!("first loan: {}", book.lend());
println!("second loan: {}", book.lend());
// Struct update syntax: take the remaining fields from another value.
let reprint = Book {
year: 2017,
..book.clone()
};
println!("{reprint:?}");
println!("same book? {}", reprint == book);
let today = Celsius(31.5);
let yesterday = Celsius(28.0);
println!(
"warmer today: {}, today is {:.1} degrees",
today > yesterday,
today.0
);
}Things Fall Apart by Chinua Achebe (1958)
first loan: true
second loan: false
Book { title: "Things Fall Apart", author: "Chinua Achebe", year: 2017, on_loan: true }
same book? false
warmer today: true, today is 31.5 degreesWalk through the new pieces:
#[derive(...)]asks the compiler to write standard implementations for you:Debugfor{:?}printing,Clonefor.clone(),PartialEqfor==,PartialOrdfor<and>,Copyfor implicit copying (allowed only when every field isCopy, which is whyBook, holding Strings, can't have it). Lesson 6 explains that these are traits.Selfinside animplblock is shorthand for the type being implemented, hereBook.- In
Self { ..., year, ... }, writingyearalone is field init shorthand foryear: year. Book::new(...)is called with::because it is an associated function: it belongs to the type but takes noself. Rust has no special constructors;newis merely the conventional name.book.label()is a method call. Rust automatically borrowsbookas&bookor&mut bookto match the method's first parameter, so you never write(&mut book).lend()...book.clone()in a struct expression copies every field not listed explicitly. Without the.clone(), the Strings would be moved out ofbook.
The first parameter of a method decides what the method may do with the value:
| Receiver | Meaning | Typical use |
|---|---|---|
&self | borrows immutably | getters, calculations, formatting |
&mut self | borrows mutably | changing fields: lend, push, reset |
self | takes ownership | converting into something else (into_string), builder steps, consuming the value |
Celsius shows why newtypes matter. A function that takes a Celsius cannot be handed a Fahrenheit reading, a distance or a price by accident, even though all of them are f64 underneath. The newtype costs nothing at run time: in memory it is an f64. Field privacy completes the picture. Fields and methods are private to their module unless marked pub, so a library can expose Book::new and label while keeping on_loan under its own control, and nobody outside can create a book in an inconsistent state.
Enums that carry data
Definition— enum
An enum defines a type by listing its variants. Each variant may carry no data, a tuple of values, or named fields. A value of the enum is exactly one variant at a time, and the only way to get at a variant's data is to match on it.
#[derive(Debug)]
enum Payment {
Cash,
Card { last_four: String },
MobileMoney { provider: String, phone: String },
Voucher(u32),
}
impl Payment {
/// The fee, in cents, for paying `amount` cents this way.
fn fee(&self, amount: u32) -> u32 {
match self {
Payment::Cash => 0,
Payment::Card { .. } => amount * 15 / 1000 + 10,
Payment::MobileMoney { .. } if amount < 10_000 => 25,
Payment::MobileMoney { .. } => 50,
Payment::Voucher(value) if *value >= amount => 0,
Payment::Voucher(_) => 5,
}
}
fn describe(&self) -> String {
match self {
Payment::Cash => String::from("cash"),
Payment::Card { last_four } => format!("card ending {last_four}"),
Payment::MobileMoney { provider, phone } => format!("{provider} from {phone}"),
Payment::Voucher(value) => format!("voucher worth {value}"),
}
}
}
fn main() {
let payments = [
Payment::Cash,
Payment::Card {
last_four: String::from("4242"),
},
Payment::MobileMoney {
provider: String::from("M-Pesa"),
phone: String::from("07** *** 381"),
},
Payment::Voucher(5_000),
];
for p in &payments {
println!(
"{:<28} fee on 120.00: {:>3} cents",
p.describe(),
p.fee(12_000)
);
}
println!("{:?}", payments[3]);
}cash fee on 120.00: 0 cents
card ending 4242 fee on 120.00: 190 cents
M-Pesa from 07** *** 381 fee on 120.00: 50 cents
voucher worth 5000 fee on 120.00: 5 cents
Voucher(5000)Compare this with the alternatives in other languages. With a single struct you would need a kind field plus optional fields for every kind (a card number that is meaningless for cash, a provider that is meaningless for vouchers), and every function would have to remember which fields are valid when. With a class hierarchy you would scatter the fee rules across four classes. Here the data each kind needs is attached to exactly that kind, and the rules for all kinds sit together in one match. Add a fifth payment method next year, and the compiler will list every match that has to learn about it.
Notice the patterns: Payment::Card { .. } matches the variant while ignoring its fields, Payment::Voucher(value) binds the voucher's value, and guards let two arms share a variant. Because self is a reference, the bindings are references too, which is why the guard compares *value (the number the reference points to) with amount.
Option: a value or nothing
Tony Hoare, who introduced the null reference in 1965, later called it his "billion-dollar mistake": in most languages any reference might secretly be null, and forgetting to check crashes the program. Rust has no null. A value that might be absent has type Option<T>, an ordinary enum from the standard library:
enum Option<T> {
None,
Some(T),
}(T is a type parameter: Option<T> works for any type T, as lesson 6 explains.) An Option<u32> is not a u32; you cannot add one to a number. To get the number out, you must say what happens when it is missing, and the compiler makes sure you do.
struct City {
name: &'static str,
country: &'static str,
population: Option<u32>, // not every record has a census figure
}
fn find<'a>(cities: &'a [City], name: &str) -> Option<&'a City> {
cities.iter().find(|city| city.name == name)
}
fn main() {
let cities = [
City {
name: "Accra",
country: "Ghana",
population: Some(2_557_000),
},
City {
name: "Hanoi",
country: "Vietnam",
population: Some(8_435_000),
},
City {
name: "Cusco",
country: "Peru",
population: None,
},
];
for wanted in ["Hanoi", "Cusco", "Atlantis"] {
match find(&cities, wanted) {
Some(city) => println!("{wanted} is in {}", city.country),
None => println!("{wanted}: no such city"),
}
}
// Combinators: transform the value inside an Option without unpacking it by hand.
let country = find(&cities, "Accra").map(|c| c.country);
println!("{country:?}");
// and_then: chain steps that can each come up empty.
let pop = find(&cities, "Cusco").and_then(|c| c.population);
println!("{pop:?}");
let shown = find(&cities, "Atlantis")
.and_then(|c| c.population)
.map(|p| p.to_string())
.unwrap_or_else(|| String::from("unknown"));
println!("Atlantis population: {shown}");
let big: Vec<&str> = cities
.iter()
.filter(|c| c.population.is_some_and(|p| p > 5_000_000))
.map(|c| c.name)
.collect();
println!("{big:?}");
}Hanoi is in Vietnam
Cusco is in Peru
Atlantis: no such city
Some("Ghana")
None
Atlantis population: unknown
["Hanoi"](The population figures are rounded illustrations, not census data. find walks the slice and returns the first city for which the closure is true, already wrapped in an Option; lesson 7 covers it and its many siblings.) match always works, but chains of combinators often read better. Each takes a closure, the |c| ... syntax you met briefly in lesson 3:
| Method | What it does |
|---|---|
map(f) | Some(x) becomes Some(f(x)); None stays None |
and_then(f) | like map, for an f that itself returns an Option; flattens the result |
filter(p) | keeps Some(x) only if p(&x) is true |
unwrap_or(v), unwrap_or_else(f) | the value, or a default (computed lazily by f) |
is_some(), is_none(), is_some_and(p) | ask without unpacking |
ok_or(e) | turns an Option into a Result, using e as the error |
Result: success or a reason for failure
When an operation can fail and the caller deserves to know why, it returns Result<T, E>: either Ok(value) or Err(error). You have already met one: "42".parse::<u32>() returns a Result. Defining your own error enum lets callers react to each kind of failure precisely.
enum TimeError {
MissingColon,
NotANumber(String),
OutOfRange { hours: u32, minutes: u32 },
}
fn explain(error: &TimeError) -> String {
match error {
TimeError::MissingColon => String::from("expected HH:MM"),
TimeError::NotANumber(part) => format!("{part:?} is not a number"),
TimeError::OutOfRange { hours, minutes } => {
format!("{hours}:{minutes:02} is not a time of day")
}
}
}
/// Parses "HH:MM" into minutes after midnight.
fn parse_time(text: &str) -> Result<u32, TimeError> {
let Some((h, m)) = text.split_once(':') else {
return Err(TimeError::MissingColon);
};
let hours: u32 = match h.parse() {
Ok(n) => n,
Err(_) => return Err(TimeError::NotANumber(h.to_string())),
};
let Ok(minutes) = m.parse::<u32>() else {
return Err(TimeError::NotANumber(m.to_string()));
};
if hours > 23 || minutes > 59 {
return Err(TimeError::OutOfRange { hours, minutes });
}
Ok(hours * 60 + minutes)
}
fn main() {
for input in ["07:45", "23:59", "7.45", "ab:10", "25:00"] {
match parse_time(input) {
Ok(total) => println!("{input} -> {total} minutes"),
Err(e) => println!("{input} -> error: {}", explain(&e)),
}
}
let departure = parse_time("09:10").unwrap_or(0);
let arrival = parse_time("11:35").unwrap_or(0);
println!("journey: {} minutes", arrival - departure);
println!("{}", parse_time("12:00").is_ok());
println!("{:?}", parse_time("bad").ok());
}07:45 -> 465 minutes
23:59 -> 1439 minutes
7.45 -> error: expected HH:MM
ab:10 -> error: "ab" is not a number
25:00 -> error: 25:00 is not a time of day
journey: 145 minutes
true
NoneThe function's signature is now honest documentation: it returns minutes or a TimeError, and the three ways it can fail are listed in one place. Result has the same family of combinators as Option (map, and_then, unwrap_or, plus map_err to transform the error), and .ok() converts it to an Option, discarding the error.
Three ways of "just getting the value" deserve a warning. unwrap() returns the value or panics, crashing the thread with a generic message. expect("why this cannot fail") does the same with your message. unwrap_or(default) never panics. In examples, tests and quick scripts, unwrap is fine. In real code, use expect only when failure would mean a bug in your own program (a regular expression literal that you know is valid, say), and handle every failure that depends on the outside world: files, networks, user input. Lesson 8 introduces the ? operator, which makes passing errors upward a single character, and the Error trait that ties error types together.
What these types cost
Structs and enums are as cheap as hand-written C. A struct is its fields laid out together (the compiler may reorder them to reduce padding). An enum is the largest variant plus a small tag that records which variant is present. And the compiler is clever about tags:
use std::mem::size_of;
#[allow(dead_code)] // the variants are never built here; we only measure the type
enum Connection {
Disconnected,
Connecting { attempt: u8 },
Connected { session_id: u64 },
}
fn main() {
let rows = [
("&u8", size_of::<&u8>()),
("Option<&u8>", size_of::<Option<&u8>>()),
("u64", size_of::<u64>()),
("Option<u64>", size_of::<Option<u64>>()),
("Connection", size_of::<Connection>()),
];
for (name, bytes) in rows {
println!("{name:<12} {bytes:>2} bytes");
}
}&u8 8 bytes
Option<&u8> 8 bytes
u64 8 bytes
Option<u64> 16 bytes
Connection 16 bytesOn this 64-bit machine a reference takes 8 bytes, and so does an optional reference. A reference can never be null, so the compiler uses the all-zero bit pattern to mean None: the niche optimisation. An Option of a reference is exactly as cheap as a nullable pointer in C, but you cannot forget to check it. A u64 has no spare bit patterns, so Option<u64> needs a tag, and alignment rounds 9 bytes up to 16. Connection likewise needs a tag beside its largest variant.
The Connection enum is also a small lesson in design. A struct with fields connected: bool, attempt: u8 and session_id: u64 could represent nonsense, such as "disconnected, with session 4471". The enum cannot: the session ID exists only in the Connected state.
Designing with structs and enums
Here is how an experienced Rust programmer might approach a small modelling task: an online shop's orders. A first draft, in the style of many languages, is one struct with flags:
struct Order {
id: u64,
paid: bool,
shipped: bool,
cancelled: bool,
receipt: Option<String>,
tracking_code: Option<String>,
cancel_reason: Option<String>,
}Count the states this allows: three booleans and three options give 64 combinations, and most of them are nonsense ("shipped but not paid", "cancelled with a tracking code"). Every function that touches an order must defend against them, and a new team member has no way to tell from the type which combinations really occur.
The idiomatic redesign splits what is always present from what depends on the stage:
struct Order {
id: u64,
items: Vec<LineItem>,
status: Status,
}
enum Status {
Placed,
Paid { receipt: String },
Shipped { receipt: String, tracking_code: String },
Cancelled { reason: String },
}Now there are exactly four states, each carrying exactly the data that makes sense for it. A function that prints a shipping label matches on Status::Shipped { tracking_code, .. } and simply has no tracking code to misuse in the other states. Transitions become methods: fn ship(&mut self, tracking_code: String) -> Result<(), ShipError> can check that the status is Paid and refuse otherwise, in one place.
Some teams go one step further and give each stage its own struct (PaidOrder, ShippedOrder), with transitions that take self by value and return the next stage: fn ship(self, code: String) -> ShippedOrder. Because the old value is moved, the compiler stops anyone from shipping the same paid order twice. This pattern, called typestate, is popular for protocols and builders; it trades some convenience (you can't keep a mixed list of orders without an enum around them) for guarantees checked at compile time.
The general lesson: when you notice booleans that are only meaningful together, or optional fields that are present "only when" something else is true, an enum is usually waiting to be found.
Common misconceptions
Misconception
"Rust enums are named integers, like in C." A C-style enum (variants with no data) is one special case. In general each variant carries its own data, and the enum is as large as its largest variant plus a tag.
Misconception
"Without classes and inheritance, Rust can't do object-oriented design." Rust has data with methods (structs and enums with impl blocks), encapsulation (privacy at module boundaries) and polymorphism (traits, next lesson). What it leaves out is implementation inheritance; it composes behaviour instead of inheriting it.
Misconception
"unwrap() is how you get a value out of an Option." It is one way, and the one that crashes on None. Prefer match, if let, let-else or a combinator that states what should happen when the value is missing. Reviewers in professional Rust code treat a stray unwrap as a question to be answered.
Misconception
"Option is slower than a nullable pointer." For references and other types with a niche, Option has exactly the same size and representation, and checking it compiles to the same null test a careful C programmer would write.
Exercises
1. Structs, enums, Option and Result
CoreComputationalWhat does this print?
fn main() {
let a = Some(4).map(|x| x * 2).filter(|x| *x > 5).unwrap_or(0);
let b = Some(2).map(|x| x * 2).filter(|x| *x > 5).unwrap_or(0);
let c = None::<i32>.map(|x| x * 2).unwrap_or(-1);
println!("{a} {b} {c}");
}
2. Structs, enums, Option and Result
Warm-upHumanA Playlist struct needs a method shuffle that reorders its songs in place. Which first parameter should it take?
3. Structs, enums, Option and Result
CoreComputationalWhat does println!("{} {}", "42".parse::<u8>().is_ok(), "300".parse::<u8>().is_err()); print?
4. Structs, enums, Option and Result
CoreComputationalUsing the Payment::fee method from the lesson, what is Payment::Card { last_four: String::from("1234") }.fee(2_000)?
5. Structs, enums, Option and Result
StretchHumanA traffic light controller stores struct Light { red: bool, amber: bool, green: bool }. Which redesign best makes illegal states unrepresentable?
6. Structs, enums, Option and Result
CoreComputationalWhy does #[derive(Clone, Copy)] work on struct Celsius(f64); but fail on struct Book { title: String, year: u16 }?
Further reading and resources
- The Rust Programming Language, chapter 5: Using Structs · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The Rust Programming Language, chapter 6: Enums and Pattern Matching · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The std::option moduleEvery Option method, with a helpful overview table at the top.
- The std::result module
- The Rust Reference: Type layoutWhat the language does and does not promise about how structs and enums sit in memory.