1. Two Ways to Group Data: AND (struct) and OR (enum)
So far, we have only worked with single primitive values like numbers and strings. Real programs need to bundle multiple values together to represent meaningful concepts.
Suppose a terminal takes an order for one kind of tea. You need the quantity, the unit price, and the shipping fee together to work out the final amount. Give the three values a name and keep them in one order.
Rust uses a struct when you want to combine multiple pieces of data with "AND".
A shipping address in an online store is a classic everyday example of a struct. You need a recipient name AND a street address AND a postal code before you have a complete address.
Because all parts exist together and their possible combinations multiply, this kind of type is called a Product Type.
For exactly one choice among several ("this OR that"), Rust uses an enum. A single payment can be in exactly one state: Pending OR Completed (with a receipt number) OR Failed (with a failure reason). A payment cannot be completed and failed at the same time. Because the total number of possible values is the sum of each option's possibilities, this kind of type is called a Sum Type.1
Each variant carries what it needs. A completed payment needs a receipt number; a failed one needs a reason. Pending needs no extra value. The same applies to order commands: changing the quantity needs a number, while showing the total doesn't.
Languages like Java and C++ rely on class inheritance to build hierarchies of related data types. Rust does not have class inheritance syntax at all.
Instead, you snap AND (struct) and OR (enum) together like building blocks to model complex domains cleanly.
2. struct and impl: Keeping Data and Methods Separate
Part 3 passed the quantity and the price separately. Here an Order holds them along with the shipping fee, and its methods change or read those values. Put the definition below in src/main.rs first. You'll append fn main() in the next section.
The struct lists the fields. The impl block defines what the type can do.2
#[derive(Debug, Clone, Copy)]
struct Order {
quantity: u32,
unit_price: u32,
shipping: u32,
}
impl Order {
fn new(quantity: u32, unit_price: u32, shipping: u32) -> Self {
Self { quantity, unit_price, shipping }
}
fn set_quantity(&mut self, quantity: u32) {
self.quantity = quantity;
}
fn set_shipping(&mut self, shipping: u32) {
self.shipping = shipping;
}
fn totals(&self) -> (u64, u64) {
let subtotal = u64::from(self.quantity) * u64::from(self.unit_price);
(subtotal, subtotal + u64::from(self.shipping))
}
}#[derive(Debug, Clone, Copy)] is an attribute. All three fields are u32, so the compiler can supply the standard implementations instead of making you write them. Debug formats the fields with {:?}, Clone gives you .clone() for an explicit copy, and Copy makes an ordinary assignment leave the original usable.
Order::new(...) has no self parameter because there is no order yet. It is an associated function: you call it on the type with ::. Self stands for Order inside this impl. Self { quantity, unit_price, shipping } fills each field with the parameter of the same name.
set_quantity and set_shipping change an existing order. Their &mut self borrows that order for writing; lowercase self refers to the particular order receiving the call. Change let mut order to let order in the next sample and the compiler will reject the first call that tries to update it.
totals(&self) only reads. It widens the quantity and price to u64 with u64::from(...) before multiplying. The last expression, (subtotal, subtotal + u64::from(self.shipping)), returns both amounts in a (u64, u64) tuple.
3. enum and match: Letting the Compiler Catch Missing Cases
Each command does one thing. SetQuantity(3) carries a new quantity; Pickup and ShowTotal need no number. A short array of commands makes it easy to rerun the same changes in the same order.
Put this code right below the Order definition in src/main.rs. Run cargo run --quiet once both pieces are in the file.
enum Command {
SetQuantity(u32),
SetShipping(u32),
Pickup,
ShowTotal,
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::SetQuantity(count) => format!("Set quantity to {}", count),
Command::SetShipping(fee) => format!("Set shipping to {} won", fee),
Command::Pickup => String::from("Switch to pickup"),
Command::ShowTotal => String::from("Show total"),
}
}
fn main() {
let mut order = Order::new(2, 1200, 500);
let script = [
Command::SetQuantity(3),
Command::SetShipping(300),
Command::ShowTotal,
Command::Pickup,
Command::ShowTotal,
];
for cmd in &script {
println!("{}", describe(cmd));
match cmd {
Command::SetQuantity(count) => order.set_quantity(*count),
Command::SetShipping(0) | Command::Pickup => order.set_shipping(0),
Command::SetShipping(fee) => order.set_shipping(*fee),
Command::ShowTotal => {
let (subtotal, total) = order.totals();
println!(" Items: {} won, total: {} won", subtotal, total);
}
}
}
}Output:
Set quantity to 3
Set shipping to 300 won
Show total
Items: 3600 won, total: 3900 won
Switch to pickup
Show total
Items: 3600 won, total: 3600 wonIn Command::SetQuantity(count) => ..., :: selects a variant of Command and the pattern gives its number the name count. This is pattern binding. When the part to the left of => matches, Rust runs the expression on the right.
format! in describe fills {} slots like println!, then returns a String. main is the part that prints it.
for cmd in &script borrows the array, so each cmd has type &Command. Binding count or fee in the match gives you a reference of type &u32. The methods take numbers, so *count and *fee read the values those references point to. This is dereferencing.
A command that sets the shipping fee to zero and choosing pickup have the same effect on this order. The | in Command::SetShipping(0) | Command::Pickup joins the two patterns. A fee of 300 goes to the next SetShipping(fee) arm instead.
The first total is 3 Γ 1200 + 300 = 3900 won. Pickup removes the shipping fee but leaves the goods at 3600. let (subtotal, total) = order.totals(); unpacks the tuple into a name for each amount.
The biggest advantage of match is exhaustiveness checking. Before your code ever runs, the compiler verifies that every variant of the enum is handled.
Add ApplyCoupon(u32) to Command and leave describe alone. The compiler points to the missing arm even if no command in the array uses a coupon.3
In other languages, forgetting a case in a switch statement without a default branch often slips through silently and turns into a subtle bug later. Rust stops that mistake at compile time.
You can add a catch-all arm _ => {} at the end of a match to handle remaining cases, but doing so disables the compiler's reminder whenever you add new variants, so use it only when you truly want to ignore future cases.
The command sample already has a number to work with. In Part 7 we'll decide what to return when a customer types a blank line or a quantity outside the allowed range. Both Option and Result are enums, just like Command.
Footnotes
- Together, struct (product type) and enum (sum type) are known as Algebraic Data Types (ADTs). The Rust Programming Language, Ch. 6: https://doc.rust-lang.org/book/ch06-00-enums.html β©
- The Rust Programming Language, Ch. 5.1 Defining and Instantiating Structs: https://doc.rust-lang.org/book/ch05-01-defining-structs.html β©
- The Rust Programming Language, Ch. 6.2 The match Control Flow Construct: https://doc.rust-lang.org/book/ch06-02-match.html β©