Lesson 09
Structuring Data
So far every value has been one number, one piece of text, one true or false, or a list of values that all have the same type. Real programs work on things that have several parts of different kinds at once. A book has a title and a page count. A temperature reading has a town and a number of degrees. This lesson is about building those values, and about saying in the type itself which shapes a value is allowed to take.
Grouping Values with a struct
Say you want to keep a title, a page count, and whether the book is out on loan. You could write three separate variables.
let title = String::from("Rust in Practice");
let pages = 312;
let borrowed = false;
This works for one book. It falls apart with two books, because now you have six variables and nothing ties the right three together. A struct ties them together. It is one type made of named parts. Each part is called a field.
struct Book {
title: String,
pages: u32,
borrowed: bool,
}
-
structstarts the definition.Bookis the name of the new type. Type names start with a capital letter. -
Each line inside the braces is one field: a name, a colon, and the type of that field.
-
u32is a whole number that cannot be negative, stored in 32 bits.boolistrueorfalse. -
This is only the definition. It creates no value yet. It tells the compiler what a
Bookis made of.
Creating and Reading a Struct
To make a value of the type, write the name of the struct and give every field a value.
struct Book {
title: String,
pages: u32,
borrowed: bool,
}
fn main() {
let item = Book {
title: String::from("Rust in Practice"),
pages: 312,
borrowed: false,
};
println!("{}", item.title);
println!("{} pages", item.pages);
println!("borrowed: {}", item.borrowed);
}
Rust in Practice
312 pages
borrowed: false
You must give a value for every field. Leave one out and the program does not compile. The order of the fields does not have to match the order in the definition, because each one is named.
A dot reads one field. item.title is the title of that book.
Changing a Field
A struct follows the same rule as any other variable. You can only change it if you declared it with mut.
fn main() {
let mut item = Book {
title: String::from("Rust in Practice"),
pages: 312,
borrowed: false,
};
item.borrowed = true;
println!("borrowed: {}", item.borrowed);
}
borrowed: true
Take the mut away and the compiler stops you.
error[E0594]: cannot assign to `item.borrowed`, as `item` is not declared as mutable
--> book.rs:14:5
|
14 | item.borrowed = true;
| ^^^^^^^^^^^^^^^^^^^^ cannot assign
|
help: consider changing this to be mutable
|
8 | let mut item = Book {
| +++
mut is all or nothing. There is no way to mark one field of a struct as changeable and the rest as fixed.
Shorthand and Struct Update
When a variable already has the same name as the field, write the name once.
#[derive(Debug)]
struct Student {
name: String,
town: String,
marks: u32,
}
fn main() {
let name = String::from("Asha");
let town = String::from("Pune");
let first = Student { name, town, marks: 71 };
let second = Student {
name: String::from("Bo"),
..first
};
println!("{second:?}");
}
Student { name: "Bo", town: "Pune", marks: 71 }
The line let first = Student { name, town, marks: 71 }; is short for this longer line.
let first = Student { name: name, town: town, marks: 71 };
Rust fills the field in from the variable that has the same name.
The two dots ..first say “take every field I have not written from first”. So second gets its own name, and the town and the marks of first. This is a move: first.town is a String, it now belongs to second, and first can no longer be used as a whole.
Printing a Struct
println!("{}", item) does not work on a struct. Rust does not know how you want it laid out. Write #[derive(Debug)] on the line above the struct and Rust writes a plain printer for you. You then print it with {:?}.
#[derive(Debug)]
struct Book {
title: String,
pages: u32,
borrowed: bool,
}
fn main() {
let item = Book {
title: String::from("Rust in Practice"),
pages: 312,
borrowed: false,
};
println!("{item:?}");
println!("{item:#?}");
}
Book { title: "Rust in Practice", pages: 312, borrowed: false }
Book {
title: "Rust in Practice",
pages: 312,
borrowed: false,
}
{:?} prints the value on one line. {:#?} prints one field per line. Use the second one when the struct is large. Both are for you, the programmer, while you work. They are not meant for the people who use your program.
Tuple Structs
Sometimes the fields need no names, because the order says everything.
struct Point(i32, i32);
fn main() {
let origin = Point(0, 0);
let corner = Point(3, 4);
println!("origin is at {}, {}", origin.0, origin.1);
println!("corner is at {}, {}", corner.0, corner.1);
}
origin is at 0, 0
corner is at 3, 4
This is a tuple struct. The fields are numbered from zero instead of named. origin.0 is the first field. Use a tuple struct only when the meaning of each position is obvious. When it is not, use named fields.
Methods
A method is a function that belongs to a type. You write it inside an impl block, and you call it with a dot on a value of that type.
#[derive(Debug)]
struct Book {
title: String,
pages: u32,
borrowed: bool,
}
impl Book {
fn new(title: &str, pages: u32) -> Book {
Book {
title: String::from(title),
pages,
borrowed: false,
}
}
fn is_long(&self) -> bool {
self.pages > 300
}
fn lend(&mut self) {
self.borrowed = true;
}
}
fn main() {
let mut item = Book::new("Rust in Practice", 312);
println!("long: {}", item.is_long());
item.lend();
println!("borrowed: {}", item.borrowed);
println!("{item:?}");
}
long: true
borrowed: true
Book { title: "Rust in Practice", pages: 312, borrowed: true }
impl Book opens a block of functions that belong to Book. The struct definition says what a book holds. The impl block says what a book can do.
The first parameter decides what kind of function it is. That first parameter can be self. self refers to the specific value the method is called on. For example, in item.is_long(), self refers to item.
self can appear in three forms: &self, &mut self, or plain self. Each form asks for the value in a different way.
If you do not want a self parameter, leave it out. The function is then called on the type itself, not on a value of it, for example Book::new(...).
| Parameter | Why it is used | Does the caller still own it? |
|---|---|---|
| &self | The method only reads the value. | Yes |
| &mut self | The method may change the value. | Yes |
| self | The method takes the value apart or gives it away. | No |
is_long takes &self, so it only borrows the book for the length of the call, and item is still yours afterwards. lend takes &mut self, so it is allowed to write to a field, and the caller must hold the value in a mut variable.
Associated Functions
new in the program above has no self. It is an associated function: it belongs to the type, not to any one value. You call it with two colons, Book::new(...), not with a dot.
Associated functions are how a type gets built. String::from is one you have already used. The name new is a convention for the function that makes a fresh value. Rust does not treat the name specially, but every Rust programmer expects new to mean that.
Key idea
A dot calls a method on a value:
item.is_long(). Two colons call a function on the type itself:Book::new("...", 312).
Enums
A struct holds all of its fields at once. Sometimes you want the opposite: a value that is exactly one out of a fixed list. A shape is a circle, or a rectangle, or a single point. It is never two of those at the same time. That is an enum.
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Point,
}
Each line is a variant: one of the shapes the value is allowed to take. A variant may carry data of its own. Circle carries one number, its radius. Rectangle carries two, a width and a height. Point carries nothing. f64 is a number with a decimal part, stored in 64 bits.
A value of type Shape is one variant and holds that variant’s data. The type is one type, so you can put a circle and a rectangle in the same array, and pass either to the same function.
Taking an Enum Apart with match
To use an enum you have to ask which variant it is. match does that. It compares a value against a list of patterns and runs the arm that fits.
#[derive(Debug)]
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Point,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Point => 0.0,
}
}
fn main() {
let shapes = [
Shape::Circle(2.0),
Shape::Rectangle(3.0, 4.0),
Shape::Point,
];
for shape in &shapes {
println!("{shape:?} has area {}", area(shape));
}
}
Circle(2.0) has area 12.56636
Rectangle(3.0, 4.0) has area 12
Point has area 0
Read one arm: Shape::Circle(radius) => 3.14159 * radius * radius.
-
Left of the
=>is the pattern. It matches when the value is a circle. -
radiusis a new name. If the arm matches, the number inside the circle is bound to that name. This is how you get the data out of a variant. -
Right of the
=>is the value the arm produces. Every arm must produce the same type. Here that isf64. -
Arms are separated by commas.
matchitself produces a value, so it can be the last line of a function.
Covering Every Case
You have to write an arm for every variant. If you forget one, the program does not compile.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value(coin: Coin) -> u32 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
}
}
error[E0004]: non-exhaustive patterns: `Coin::Quarter` not covered
--> coin.rs:9:11
|
9 | match coin {
| ^^^^ pattern `Coin::Quarter` not covered
|
note: `Coin` defined here
--> coin.rs:1:6
|
1 | enum Coin {
| ^^^^
...
5 | Quarter,
| ------- not covered
This check prevents a common mistake. Add a variant to the enum a year later and the compiler lists every match in the program that now has a hole in it.
Key idea
A
matchmust handle every possible value. The compiler counts the cases for you, so a case can never be forgotten by accident.
Patterns for Numbers
match works on any value, not only on enums. A pattern can be one value, several values, or a range.
fn describe(n: i32) -> &'static str {
match n {
0 => "zero",
1 | 2 | 3 => "small",
4..=9 => "medium",
_ => "large",
}
}
fn main() {
for n in [0, 2, 7, 40] {
println!("{n} is {}", describe(n));
}
}
0 is zero
2 is small
7 is medium
40 is large
-
1 | 2 | 3matches any one of those three numbers. -
4..=9matches every number from 4 to 9, including both ends. -
_matches anything. Put it last. It is how you cover all the cases you did not list one by one. -
Arms are tried from the top down. The first one that fits wins, so a
_in the middle would make every arm below it useless.
The Option Type
Many languages have a value called null that means “nothing here”. It is a common source of crashes, because you can use it by mistake anywhere a real value was expected. Rust has no null. It has an enum instead.
enum Option<T> {
Some(T),
None,
}
Option is in the standard library, so you do not write this definition yourself. T stands for any type: Option<i32> is a number that may be missing, Option<String> is text that may be missing. Some(T) holds a value. None holds nothing.
You do not write Option::Some and Option::None. Some and None are available by name everywhere.
fn first_word(text: &str) -> Option<&str> {
text.split_whitespace().next()
}
fn main() {
let sentence = String::from("hello there");
let empty = String::new();
match first_word(&sentence) {
Some(word) => println!("first word: {word}"),
None => println!("no words"),
}
match first_word(&empty) {
Some(word) => println!("first word: {word}"),
None => println!("no words"),
}
}
first word: hello
no words
The return type Option<&str> says in the signature that this function sometimes has no answer. Empty text has no first word. The caller cannot ignore that: to reach the text inside, they have to write the None arm as well.
Key idea
An
Option<i32>is not ani32. You cannot add it to a number until you have taken it apart and dealt with the missing case. That is why Rust programs do not crash on missing values.
A Fallback Value with unwrap_or
Writing a full match for every Option is heavy. unwrap_or gives you the value inside, or a value you choose when there is nothing inside.
The program below keeps its numbers in a list. vec! makes a list from the values written inside the square brackets. A list can grow and shrink while the program runs, so its items are kept on the heap. The exclamation mark is part of the name, the same as in println!.
fn main() {
let marks = vec![71, 64, 88];
println!("{}", marks.get(0).copied().unwrap_or(0));
println!("{}", marks.get(9).copied().unwrap_or(0));
}
71
0
marks.get(0) asks for the first item of the list. It gives back an Option, because the position you asked for may not exist. Position 9 does not exist here, so the second line falls back to 0.
if let and while let
if let is a short match for when you care about one pattern and nothing else.
fn main() {
let age: Option<u32> = Some(30);
if let Some(years) = age {
println!("age is {years}");
} else {
println!("age is unknown");
}
}
age is 30
Read it as: if age fits the pattern Some(years), bind the number to years and run the block. The else block runs when it does not fit. The else is optional. Leave it out when there is nothing to do in the other case.
while let does the same thing in a loop. It keeps going while the pattern still fits.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("took {top}");
}
println!("stack is empty");
}
took 3
took 2
took 1
stack is empty
stack.pop() removes the last item and gives back Some of it. When the list is empty it gives back None, the pattern no longer fits, and the loop stops. Without while let you would write a loop with a match and a break inside it.
Key idea
Use
matchwhen you must handle every case. Useif letwhen you care about one case. Usewhile letto repeat while one case keeps happening.
The Result Type
Option says a value may be missing. It does not say why. When an operation can fail and the reason matters, use Result.
enum Result<T, E> {
Ok(T),
Err(E),
}
T is the type of the answer when the work succeeds. E is the type of the description when it fails. Like Some and None, the two names Ok and Err are available everywhere without a prefix.
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("cannot divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10.0, 4.0) {
Ok(value) => println!("answer: {value}"),
Err(message) => println!("failed: {message}"),
}
match divide(10.0, 0.0) {
Ok(value) => println!("answer: {value}"),
Err(message) => println!("failed: {message}"),
}
}
answer: 2.5
failed: cannot divide by zero
The function never crashes and never returns a wrong number. It hands the caller either an answer or a reason. The caller decides what to do about it. Here the error type is a String. Real libraries use their own error types, but the shape is the same.
Recoverable and Unrecoverable Failures
Not every failure deserves the same treatment. Rust splits them in two.
A recoverable failure is one the program can sensibly react to. A file is missing, so ask for another name. Text does not parse as a number, so tell the user and read the line again. Return a Result for these.
An unrecoverable failure is a mistake in the program itself. An index past the end of a list. A state that your own code should have made impossible. There is nothing sensible to do, so stop. panic! does that.
fn withdraw(balance: u32, amount: u32) -> u32 {
if amount > balance {
panic!("asked for {amount} but the balance is only {balance}");
}
balance - amount
}
fn main() {
println!("left: {}", withdraw(100, 30));
println!("left: {}", withdraw(100, 500));
}
left: 70
thread 'main' (558514) panicked at bank.rs:3:9:
asked for 500 but the balance is only 100
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The first call printed its answer. The second called panic!. The program printed the message, the file and the line it happened on, and stopped. No line after it ran.
Key idea
Return a
Resultwhen the caller could reasonably deal with the failure. Callpanic!only when carrying on would be wrong. A library should almost always return aResultand let the program above it decide.
unwrap and expect
unwrap takes the value out of an Ok or a Some. If the value is an Err or a None instead, it panics.
fn main() {
let text = "42";
let number: i32 = text.parse().unwrap();
println!("number is {number}");
let bad = "forty";
let broken: i32 = bad.parse().unwrap();
println!("never printed: {broken}");
}
number is 42
thread 'main' (558445) panicked at unwrap.rs:7:35:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
parse turns text into a number. It returns a Result, because the text may not be a number. "forty" is not, so unwrap panicked and the last line never ran.
expect does the same thing and lets you write the message.
fn main() {
let text = "seven";
let number: i32 = text.parse().expect("not a whole number");
println!("{number}");
}
thread 'main' (560451) panicked at expect.rs:3:36:
not a whole number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Prefer expect over unwrap. When the program does stop, the message tells you which of the fifty unwrap calls in your code was the one that failed. Both are fine in small experiments and in tests. In a program other people run, handle the error instead.
The ? Operator
Most of the time a function that hits an error has nothing useful to do with it. It just wants to hand it to its caller. Written out with match, that is four lines every time. The ? operator is those four lines in one character.
use std::num::ParseIntError;
fn add_text(a: &str, b: &str) -> Result<i32, ParseIntError> {
let first: i32 = a.parse()?;
let second: i32 = b.parse()?;
Ok(first + second)
}
fn main() {
match add_text("20", "22") {
Ok(total) => println!("total: {total}"),
Err(error) => println!("failed: {error}"),
}
match add_text("20", "two") {
Ok(total) => println!("total: {total}"),
Err(error) => println!("failed: {error}"),
}
}
total: 42
failed: invalid digit found in string
Put ? after anything that gives back a Result. It does one of two things.
-
The value is
Ok.?takes what is inside and the line carries on.a.parse()?produces the number itself, not aResult. -
The value is
Err.?returns from the function immediately, handing that sameErrback to the caller. No later line runs.
In the second call "two" is not a number, so the first ? returned the error at once. second was never worked out and the addition never happened.
There are two conditions on ?. The function it appears in must itself return a Result, because that is what ? returns on failure. And the error type must match the one in the function’s signature. ? also works on Option in a function that returns an Option, where it returns None early in the same way.
use std::num::ParseIntError; at the top brings the name of that error type into the file so the signature can use it. ParseIntError is the error parse produces when the text is not a number.
Everything Together
This program uses all of the lesson. A struct holds one reading. An enum names the three bands a temperature can fall into. An associated function builds a reading from a line of text and returns a Result, so a bad line is reported and not a crash.
#[derive(Debug)]
struct Reading {
town: String,
degrees: i32,
}
enum Level {
Cold,
Mild,
Hot,
}
impl Reading {
fn parse(line: &str) -> Result<Reading, String> {
let mut parts = line.split(' ');
let town = match parts.next() {
Some(word) => String::from(word),
None => return Err(String::from("no town in the line")),
};
let number = match parts.next() {
Some(word) => word,
None => return Err(format!("no temperature for {town}")),
};
let degrees: i32 = match number.parse() {
Ok(value) => value,
Err(_) => return Err(format!("{number} is not a number")),
};
Ok(Reading { town, degrees })
}
fn level(&self) -> Level {
if self.degrees < 15 {
Level::Cold
} else if self.degrees < 30 {
Level::Mild
} else {
Level::Hot
}
}
}
fn report(line: &str) {
let reading = match Reading::parse(line) {
Ok(value) => value,
Err(message) => {
println!("bad line: {message}");
return;
}
};
let word = match reading.level() {
Level::Cold => "cold",
Level::Mild => "mild",
Level::Hot => "hot",
};
let degrees = reading.degrees;
println!("{} is {word} at {degrees} degrees", reading.town);
}
fn main() {
report("Pune 31");
report("Oslo 4");
report("Delhi warm");
report("Lima");
}
Pune is hot at 31 degrees
Oslo is cold at 4 degrees
bad line: warm is not a number
bad line: no temperature for Lima
Four parts of this program need extra explanation.
-
line.split(' ')cuts the line at every space and hands back the pieces one at a time.parts.next()asks for the next piece. It returns anOption, because there may be no piece left. -
return Err(...)leavesparseat once with a failure. This is what?does for you when the error types already agree. Here they do not:nextgives anOptionandnumber.parsegives aParseIntError, while the function reports errors as aString. -
Err(_)matches any error and throws the details away. The_is a pattern that fits anything and binds no name. -
format!builds aStringthe same wayprintln!builds a line, but it gives the text back instead of printing it.
Reference
| Written as | What it does |
|---|---|
| struct Book { … } | Define a type made of named fields. |
| Book { pages: 312 } | Create a value of that type. |
| item.pages | Read or write one field. |
| struct Point(i32, i32) | Define a struct whose fields are numbered. |
| #[derive(Debug)] | Let the type be printed with {:?}. |
| impl Book { … } | Open the block of functions belonging to the type. |
| fn area(&self) | A method that reads the value. |
| fn lend(&mut self) | A method that changes the value. |
| fn new(…) -> Book | An associated function. Called as Book::new. |
| enum Shape { … } | Define a type that is one of a fixed list. |
| match value { … } | Pick one arm. Every case must be covered. |
| _ => … | The arm that matches anything left over. |
| if let Some(x) = v | Run a block only if one pattern fits. |
| while let Some(x) = v | Loop while one pattern keeps fitting. |
| Option<T> | Some(T) or None. A value that may be absent. |
| Result<T, E> | Ok(T) or Err(E). Work that may fail. |
| v.unwrap() | The value inside, or panic. |
| v.expect(”…”) | The value inside, or panic with your message. |
| v.unwrap_or(0) | The value inside, or the fallback you give. |
| value? | The value inside, or return the error at once. |
| panic!(”…”) | Stop the program with a message. |
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →