Structs, Enums and impl Blocks: Modelling the Turbine
Model data with Rust structs, methods in impl blocks, and enums that carry data, and use match to handle every state of a turbine, with Debug printing and derived traits.
In this lesson you will
- Define structs and methods
- Use associated functions as constructors
- Define enums that carry data
- Derive Debug, Clone and PartialEq
About 28 minutes
Giving the data a shape
Until now Ines has kept her turbine data in loose variables. A real program needs a type that says what a turbine is, and Rust gives two tools for that. A struct groups named fields, such as an id, a name and a power output, into one type. An enum lists the several forms a value can take, for example that a turbine is running, stopped for maintenance or faulted with an error code, and unlike the enums of C, each variant can carry its own data.
Methods go in an impl block. A method takes self as its first parameter: &self to read, &mut self to change, or self to consume the value. A function without self, such as new, is an associated function, called with the double colon, and it is the Rust way to write a constructor, since the language has no special constructor syntax. The attribute derive asks the compiler to write common traits for you: Debug lets the value be printed with {:?}, Clone gives a clone method, and PartialEq allows comparison with ==. Because match must be exhaustive, adding a new variant to an enum makes the compiler list every place that has to handle it.
| Item | Syntax |
|---|---|
| Struct | struct Turbine { id: u32, kw: f64 } |
| Method | fn rated(&self) -> bool |
| Associated function | Turbine::new(1, 2.5) |
| Enum with data | enum Status { Running(f64), Fault { code: u32 } } |
| Derive | #[derive(Debug, Clone, PartialEq)] |
#[derive(Debug, Clone, PartialEq)]
enum Status {
Running { kw: f64 },
Maintenance,
Fault { code: u32 },
}
#[derive(Debug, Clone)]
struct Turbine {
id: u32,
name: String,
rated_kw: f64,
status: Status,
}
impl Turbine {
fn new(id: u32, name: &str, rated_kw: f64) -> Self {
Turbine { id, name: name.to_string(), rated_kw, status: Status::Maintenance }
}
fn start(&mut self, kw: f64) {
self.status = Status::Running { kw };
}
fn output(&self) -> f64 {
match &self.status {
Status::Running { kw } => *kw,
Status::Maintenance => 0.0,
Status::Fault { .. } => 0.0,
}
}
fn load_percent(&self) -> f64 {
self.output() / self.rated_kw * 100.0
}
fn describe(&self) -> String {
match &self.status {
Status::Running { kw } => format!("{} runs at {} kW", self.name, kw),
Status::Maintenance => format!("{} is in maintenance", self.name),
Status::Fault { code } => format!("{} has fault code {}", self.name, code),
}
}
}
fn main() {
let mut a = Turbine::new(1, "North-1", 2500.0);
println!("{}", a.describe());
a.start(1875.0);
println!("{} (load {:.1}%)", a.describe(), a.load_percent());
let mut b = a.clone();
b.name = String::from("North-2");
b.status = Status::Fault { code: 42 };
println!("{}", b.describe());
println!("a is still {:?}, b is {:?}", a.status, b.status);
println!("equal statuses? {} | same status as itself? {}", a.status == b.status, b.status == b.status.clone());
println!("debug print: {:?}", a);
let farm = vec![a.clone(), b.clone(), Turbine::new(3, "South-1", 3000.0)];
let total: f64 = farm.iter().map(|t| t.output()).sum();
let faults = farm.iter().filter(|t| matches!(t.status, Status::Fault { .. })).count();
println!("farm output {} kW, {} faulted, {} turbines, id sum {}", total, faults, farm.len(), farm.iter().map(|t| t.id).sum::<u32>());
}
North-1 is in maintenance
North-1 runs at 1875 kW (load 75.0%)
North-2 has fault code 42
a is still Running { kw: 1875.0 }, b is Fault { code: 42 }
equal statuses? false | same status as itself? true
debug print: Turbine { id: 1, name: "North-1", rated_kw: 2500.0, status: Running { kw: 1875.0 } }
farm output 1875 kW, 1 faulted, 3 turbines, id sum 5
The constructor Turbine::new created North-1 in the Maintenance state, and its describe method said so: “North-1 is in maintenance”. After start(1875.0) the status became Running with that power, and the load, output divided by the rated 2,500 kW, was 75.0 percent. The clone b was independent of a: renaming b and putting it into a fault with code 42 did not touch a, which still held Running { kw: 1875.0 }, while b held Fault { code: 42 }. Because both derive PartialEq, the two statuses compare as unequal (false), and a status equals its own clone (true).
The derived Debug output printed the whole struct, as Turbine { id: 1, name: “North-1”, rated_kw: 2500.0, status: Running { kw: 1875.0 } }, which is invaluable when you debug, and costs one line of code. Last, a vector of three turbines was summarised with iterators: the total output was 1875 kW, since only the running one contributes, 1 turbine was faulted according to the matches! macro, the farm has 3 turbines, and their ids sum to 5.
Notice that the method output uses match on &self.status, so it borrows the status instead of moving it out of the struct. If the match had been on self.status directly, the borrow checker would complain, because a match with bindings can move data out of a value that you only borrow. Borrowing in the match with a reference is the usual fix, and the compiler’s message says so.
Check by hand: 1875 divided by 2500 is 0.75, so the load is 75.0 percent. The farm output is 1875 plus 0 for the faulted turbine plus 0 for the one in maintenance, and the ids are 1 + 1 + 3 = 5, because the clone b kept the id of a: renaming it did not change its id, which is a reminder that a clone is an exact copy until you change it. The enum makes illegal states impossible: a turbine cannot be running and have a fault code at the same time, because each variant carries only its own data.
A struct with the booleans running, faulted and maintenance allows nonsense combinations such as running and faulted at once. An enum allows only the states you listed, and the compiler makes you handle each.
Start with derive for Debug, Clone and PartialEq. Write your own implementation only when the default behaviour is wrong, for example comparing floats with a tolerance.
Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording.
Practice
Add a Stopped variant that carries a reason string. Compile, and watch the compiler list the matches that now need an arm. Then add a method fault_code that returns an Option, Some only for a fault.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does impl do?
- Imports a module
- Defines methods and associated functions for a type
- Compiles a file
- Creates a trait
Methods live in impl blocks.
What is Turbine::new?
- An associated function used as a constructor
- A macro
- A method with self
- A field
No self parameter, so called with ::.
What can an enum variant carry in Rust?
- Its own data
- Nothing
- Only integers
- Only strings
Unlike C enums.
What does derive(Debug) give you?
- Faster code
- Cloning
- Threading
- Printing with {:?}
Debug is the developer-oriented formatting.
Why match on &self.status instead of self.status?
- It is faster
- It is required for enums
- It prints it
- To borrow instead of moving out
Avoids moving data out of borrowed self.
Summary
- A struct groups named fields; an enum lists variants that can carry data.
- Methods go in impl blocks; new is an associated function by convention.
- derive adds Debug, Clone and PartialEq automatically.
- Enums make illegal states unrepresentable, and match checks every case.
Questions
Does Rust have classes?
No. Structs and enums hold data, impl blocks add methods, and traits describe shared behaviour. There is no inheritance.
What is Self?
An alias for the type being implemented, so Self can stand for Turbine inside impl Turbine.
How do I hide fields?
Fields are private to their module by default. Mark them pub to expose them, and provide methods for controlled access.
