medium.com 6 min read Original Source

Rust Enums Do Something Java Enums Simply Cannot

Not a Medium member? Read it here for free

This article introduces two fundamental data structures in Rust: structs and enums. Structs allow you to group related data together, creating complex data types. Enums let you define a type that can hold one of several possible values, representing different states or options. These, combined with pattern matching, make your code expressive and type-safe.

Part 1: Structs — Organising Data

Structs are like blueprints for creating custom data types. They are used to group related values under a single name.

1.1 Defining and Instantiating Structs

#[derive(Debug)] // This allows us to print the struct using {:?}
struct Spaceship {
    name: String,
    fuel: u32,
    is_docked: bool,
}
fn main() {
    let mut ship = Spaceship {
        name: String::from("Voyager"),
        fuel: 100,
        is_docked: false,
    };
    println!("{:?}", ship); // Output: Spaceship { name: "Voyager", fuel: 100, is_docked: false }
    ship.fuel -= 20; // Deduct fuel.  `ship` must be `mut` to allow modification.
    ship.is_docked = true; // Change docking status.
    println!("{:?}", ship); // Output: Spaceship { name: "Voyager", fuel: 80, is_docked: true }
}
#[derive(Debug)] // This allows us to print the struct using {:?}
struct Spaceship {
    name: String,
    fuel: u32,
    is_docked: bool,
}
fn main() {
    let mut ship = Spaceship {
        name: String::from("Voyager"),
        fuel: 100,
        is_docked: false,
    };
    println!("{:?}", ship); // Output: Spaceship { name: "Voyager", fuel: 100, is_docked: false }
    ship.fuel -= 20; // Deduct fuel.  `ship` must be `mut` to allow modification.
    ship.is_docked = true; // Change docking status.
    println!("{:?}", ship); // Output: Spaceship { name: "Voyager", fuel: 80, is_docked: true }
}
  • #[derive(Debug)]: This attribute allows you to print the struct’s contents using the {:?} format specifier in println!. It’s very useful for debugging.
  • struct Spaceship { ... }: This defines the Spaceship struct with three fields: name (a String), fuel (a u32 – an unsigned 32-bit integer), and is_docked (a bool).
  • let mut ship = Spaceship { ... };: This creates an instance of the Spaceship struct and assigns it to the variable ship. The mut keyword is crucial; structs are immutable by default in Rust. If you don’t use mut, you won’t be able to change the fields of ship later.
  • ship.fuel -= 20;: This modifies the fuel field of the ship instance. Because ship was declared with mut, we can change its fields.

Mutability: As discussed in previous article, In Rust, variables are immutable by default. This helps prevent accidental modification of data. To make a struct (or any variable) mutable, you must use the mut keyword. It’s important to understand that the entire struct is either mutable or immutable. You cannot have some fields mutable and others immutable within the same struct instance.

1.2 Structs vs. Tuple Structs

Rust offers another way to create data structures called tuple structs. These are like structs, but their fields don’t have names.

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}
#[derive(Debug)]
struct Coordinates(i32, i32, i32); // Tuple struct
fn main() {
    let alice = Person {
        name: String::from("Alice"),
        age: 30,
    };
    let origin = Coordinates(0, 0, 0);
    println!("{:?}", alice); // Output: Person { name: "Alice", age: 30 }
    println!("{:?}", origin); // Output: Coordinates(0, 0, 0)
}
#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}
#[derive(Debug)]
struct Coordinates(i32, i32, i32); // Tuple struct
fn main() {
    let alice = Person {
        name: String::from("Alice"),
        age: 30,
    };
    let origin = Coordinates(0, 0, 0);
    println!("{:?}", alice); // Output: Person { name: "Alice", age: 30 }
    println!("{:?}", origin); // Output: Coordinates(0, 0, 0)
}
  • struct Person { ... }: This is a regular struct with named fields. This is generally preferred because the names make the code more readable and self-documenting.
  • struct Coordinates(i32, i32, i32);: This is a tuple struct. It’s similar to a tuple (like (i32, i32, i32)), but it has a name (Coordinates). Tuple structs are useful when you have a simple data structure and the field names are obvious from the context (e.g., coordinates, RGB colors). They are more concise than regular structs.

Rule of Thumb: Use regular structs when the field names add clarity. Use tuple structs when the field names are less important or obvious from the context.

1.3 Associated Functions & Methods

You can define functions that are associated with a struct using impl blocks. These can be either associated functions (often used as constructors) or methods (which operate on an instance of the struct).

Self {
Spaceship {
name,
fuel,
is_docked: false, // Default value
}
}
// Method (operates on an instance of the struct)
fn launch(&mut self) { // `&mut self` means this method can modify the struct
if self.fuel > 0 {
self.is_docked = false;
println!("{} has launched!", self.name);
} else {
println!("{} has insufficient fuel to launch!", self.name);
}
}
}
fn main() {
let mut ship = Spaceship::new(String::from("Falcon"), 75); // Use the associated function `new`
ship.launch(); // Call the `launch` method
println!("{:?}", ship);
let mut empty_ship = Spaceship::new(String::from("Empty"), 0);
empty_ship.launch();
println!("{:?}", empty_ship);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug)]
struct Spaceship {
    name: String,
    fuel: u32,
    is_docked: bool,
}
impl Spaceship {
    // Associated function (often acts as a constructor)
    fn new(name: String, fuel: u32) -> Self {
        Spaceship {
            name,
            fuel,
            is_docked: false, // Default value
        }
    }
    // Method (operates on an instance of the struct)
    fn launch(&mut self) { // `&mut self` means this method can modify the struct
        if self.fuel > 0 {
            self.is_docked = false;
            println!("{} has launched!", self.name);
        } else {
          println!("{} has insufficient fuel to launch!", self.name);
        }
    }
}
fn main() {
    let mut ship = Spaceship::new(String::from("Falcon"), 75); // Use the associated function `new`
    ship.launch(); // Call the `launch` method
    println!("{:?}", ship);
    let mut empty_ship = Spaceship::new(String::from("Empty"), 0);
    empty_ship.launch();
    println!("{:?}", empty_ship);
}
#[derive(Debug)]
struct Spaceship {
    name: String,
    fuel: u32,
    is_docked: bool,
}
impl Spaceship {
    // Associated function (often acts as a constructor)
    fn new(name: String, fuel: u32) -> Self {
        Spaceship {
            name,
            fuel,
            is_docked: false, // Default value
        }
    }
    // Method (operates on an instance of the struct)
    fn launch(&mut self) { // `&mut self` means this method can modify the struct
        if self.fuel > 0 {
            self.is_docked = false;
            println!("{} has launched!", self.name);
        } else {
          println!("{} has insufficient fuel to launch!", self.name);
        }
    }
}
fn main() {
    let mut ship = Spaceship::new(String::from("Falcon"), 75); // Use the associated function `new`
    ship.launch(); // Call the `launch` method
    println!("{:?}", ship);
    let mut empty_ship = Spaceship::new(String::from("Empty"), 0);
    empty_ship.launch();
    println!("{:?}", empty_ship);
}
  • impl Spaceship { ... }: This block defines the implementation for the Spaceship struct.
  • fn new(name: String, fuel: u32) -> Self { ... }: This is an associated function. It’s called using Spaceship::new(...). It’s common to use associated functions as constructors to create new instances of the struct. Self is an alias for the struct type (Spaceship in this case).
  • fn launch(&mut self) { ... }: This is a method. It’s called on an instance of the struct (e.g., ship.launch()). &mut self means the method takes a mutable reference to the struct instance, allowing it to modify the struct’s fields. If you only need to read the fields and not modify them, you’d use &self.

Part 2: Enums — Modelling Variants

Enums (enumerations) allow you to define a type that can be one of several distinct variants. They are used to represent different states or options.

2.1 Enums with Data

#[derive(Debug)]
enum Measurement {
    Temperature(f32),                // Tuple variant
    Pressure(f32, String),       // Tuple variant with additional data
    Coordinates { x: f64, y: f64 }, // Struct-like variant
}
fn main() {
    let temp = Measurement::Temperature(23.5);
    let pressure = Measurement::Pressure(1013.25, String::from("hPa"));
    let location = Measurement::Coordinates { x: 34.05, y: -118.24 };
    println!("{:?}", temp);      // Output: Temperature(23.5)
    println!("{:?}", pressure);  // Output: Pressure(1013.25, "hPa")
    println!("{:?}", location);    // Output: Coordinates { x: 34.05, y: -118.24 }
}
#[derive(Debug)]
enum Measurement {
    Temperature(f32),                // Tuple variant
    Pressure(f32, String),       // Tuple variant with additional data
    Coordinates { x: f64, y: f64 }, // Struct-like variant
}
fn main() {
    let temp = Measurement::Temperature(23.5);
    let pressure = Measurement::Pressure(1013.25, String::from("hPa"));
    let location = Measurement::Coordinates { x: 34.05, y: -118.24 };
    println!("{:?}", temp);      // Output: Temperature(23.5)
    println!("{:?}", pressure);  // Output: Pressure(1013.25, "hPa")
    println!("{:?}", location);    // Output: Coordinates { x: 34.05, y: -118.24 }
}
  • enum Measurement { ... }: This defines the Measurement enum. It can be one of three variants: Temperature, Pressure, or Coordinates.
  • Variants: Each variant can optionally hold data. Temperature holds a single f32 value. Pressure holds an f32 and a String. Coordinates is a struct-like variant with named fields x and y.

Part 3: Pattern Matching — The match Control Flow

Pattern matching feature in Rust that allows you to match a value against a series of patterns. It’s most commonly used with enums, but it can also be used with other types.

3.1 Matching on Enums

Pattern matching in Rust allows for elegant and efficient control flow by destructuring complex data structures and handling multiple cases succinctly.

println!("All systems go."),
AlertStatus::Warning => println!("Check systems."),
AlertStatus::Critical => println!("Evacuate immediately!"),
}
}
fn main() {
let status = AlertStatus::Warning;
handle_alert(status); // Output: Check systems.
let another_status = AlertStatus::Critical;
handle_alert(another_status); // Output: Evacuate immediately!
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug)]
enum AlertStatus {
    Normal,
    Warning,
    Critical,
}
fn handle_alert(status: AlertStatus) {
    match status {
        AlertStatus::Normal => println!("All systems go."),
        AlertStatus::Warning => println!("Check systems."),
        AlertStatus::Critical => println!("Evacuate immediately!"),
    }
}
fn main() {
    let status = AlertStatus::Warning;
    handle_alert(status); // Output: Check systems.
    let another_status = AlertStatus::Critical;
    handle_alert(another_status); // Output: Evacuate immediately!
}
#[derive(Debug)]
enum AlertStatus {
    Normal,
    Warning,
    Critical,
}
fn handle_alert(status: AlertStatus) {
    match status {
        AlertStatus::Normal => println!("All systems go."),
        AlertStatus::Warning => println!("Check systems."),
        AlertStatus::Critical => println!("Evacuate immediately!"),
    }
}
fn main() {
    let status = AlertStatus::Warning;
    handle_alert(status); // Output: Check systems.
    let another_status = AlertStatus::Critical;
    handle_alert(another_status); // Output: Evacuate immediately!
}
  • match status { ... }: The match expression takes a value (status in this case) and compares it against a series of patterns.
  • AlertStatus::Normal => ...: This is a pattern. If status is equal to AlertStatus::Normal, the code to the right of the => is executed. The same applies to the other patterns.

Exhaustiveness: match expressions in Rust must be exhaustive. This means you must handle all possible variants of the enum. If you don’t, the compiler will give you an error. This ensures that you don’t forget to handle any cases, making your code safer.

3.2 Matching with Guards

You can add conditions to your patterns using guards. This allows you to match on a variant only if a certain condition is met.

println!("Out of fuel!"),
f if f println!("Low fuel: {}%", f), // Guard: f must be less than 20
_ => println!("Fuel OK."), // _ is a wildcard pattern, matching anything
}
}
fn main() {
check_fuel(0); // Output: Out of fuel!
check_fuel(15); // Output: Low fuel: 15%
check_fuel(50); // Output: Fuel OK.
check_fuel(1); // Output: Low fuel: 1%
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn check_fuel(fuel: u32) {
    match fuel {
        0 => println!("Out of fuel!"),
        f if f < 20 => println!("Low fuel: {}%", f), // Guard: f must be less than 20
        _ => println!("Fuel OK."), // _ is a wildcard pattern, matching anything
    }
}
fn main() {
    check_fuel(0);   // Output: Out of fuel!
    check_fuel(15);  // Output: Low fuel: 15%
    check_fuel(50);  // Output: Fuel OK.
    check_fuel(1); // Output: Low fuel: 1%
}
fn check_fuel(fuel: u32) {
    match fuel {
        0 => println!("Out of fuel!"),
        f if f < 20 => println!("Low fuel: {}%", f), // Guard: f must be less than 20
        _ => println!("Fuel OK."), // _ is a wildcard pattern, matching anything
    }
}
fn main() {
    check_fuel(0);   // Output: Out of fuel!
    check_fuel(15);  // Output: Low fuel: 15%
    check_fuel(50);  // Output: Fuel OK.
    check_fuel(1); // Output: Low fuel: 1%
}
  • f if f < 20 => ...: This pattern matches if fuel is assigned to f and f is less than 20.
  • _ => …: This is the wildcard pattern. It matches anything that hasn’t been matched by the other patterns. It’s often used as the last pattern in a match expression to handle the default case.

Self-Check Before the Exercise

  • Struct vs. Tuple Struct: Use regular structs when field names add clarity. Use tuple structs when field names are less important or obvious from the context.
  • Option<T>: Option<T> is an enum that can be either Some(T) (containing a value of type T) or None (representing the absence of a value). It’s Rust’s way of handling situations where a value might be missing, avoiding null pointer errors.
  • Filtering a Vec<enum>: You can use iterators and the filter method to find specific variants in a vector of enums. You would likely use pattern matching inside the filter closure.

Practice Exercise: Galactic Database (Complete Solution)

<button data-code="#[derive(Debug)]
enum ShipClass {
Cargo,
Fighter,
Explorer,
}
#[derive(Debug)]
struct SpacePort {
ships: Vec,
}
impl SpacePort {
fn new() -> Self {
SpacePort { ships: Vec::new() }
}
fn register_ship(&mut self, name: String, class: ShipClass) {
self.ships.push((name, class));
}
fn list_ships_by_class(&self, class: ShipClass) {
for (name, ship_class) in &self.ships {
if std::mem::discriminant(ship_class) == std::mem::discriminant(&class) {
println!("{}", name);
}
}
}
}
fn main() {
let mut port = SpacePort::new();
port.register_ship(String::from("Andromeda"), ShipClass::Explorer);
port.register_ship(String::from("Titan"), ShipClass::Cargo);
port.register_ship(String::from("Falcon"), ShipClass::Fighter);
println!("Fighter ships:");
port.list_ships_by_class(ShipClass::Fighter); // Output: Falcon
println!("All ships:");
for (name, class) in &port.ships {
println!("{}: {:?}", name, class);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug)]
enum ShipClass {
    Cargo,
    Fighter,
    Explorer,
}
#[derive(Debug)]
struct SpacePort {
    ships: Vec<(String, ShipClass)>,
}
impl SpacePort {
    fn new() -> Self {
        SpacePort { ships: Vec::new() }
    }
    fn register_ship(&mut self, name: String, class: ShipClass) {
        self.ships.push((name, class));
    }
    fn list_ships_by_class(&self, class: ShipClass) {
        for (name, ship_class) in &self.ships {
            if std::mem::discriminant(ship_class) == std::mem::discriminant(&class) {
                println!("{}", name);
            }
        }
    }
}
fn main() {
    let mut port = SpacePort::new();
    port.register_ship(String::from("Andromeda"), ShipClass::Explorer);
    port.register_ship(String::from("Titan"), ShipClass::Cargo);
    port.register_ship(String::from("Falcon"), ShipClass::Fighter);
    println!("Fighter ships:");
    port.list_ships_by_class(ShipClass::Fighter); // Output: Falcon
    println!("All ships:");
    for (name, class) in &port.ships {
        println!("{}: {:?}", name, class);
    }
}
#[derive(Debug)]
enum ShipClass {
    Cargo,
    Fighter,
    Explorer,
}
#[derive(Debug)]
struct SpacePort {
    ships: Vec<(String, ShipClass)>,
}
impl SpacePort {
    fn new() -> Self {
        SpacePort { ships: Vec::new() }
    }
    fn register_ship(&mut self, name: String, class: ShipClass) {
        self.ships.push((name, class));
    }
    fn list_ships_by_class(&self, class: ShipClass) {
        for (name, ship_class) in &self.ships {
            if std::mem::discriminant(ship_class) == std::mem::discriminant(&class) {
                println!("{}", name);
            }
        }
    }
}
fn main() {
    let mut port = SpacePort::new();
    port.register_ship(String::from("Andromeda"), ShipClass::Explorer);
    port.register_ship(String::from("Titan"), ShipClass::Cargo);
    port.register_ship(String::from("Falcon"), ShipClass::Fighter);
    println!("Fighter ships:");
    port.list_ships_by_class(ShipClass::Fighter); // Output: Falcon
    println!("All ships:");
    for (name, class) in &port.ships {
        println!("{}: {:?}", name, class);
    }
}
  • std::mem::discriminant(): This function returns a value that uniquely identifies the variant of an enum. We use it here to compare the ship_class in the vector with the class we’re looking for. This is a robust way to compare enum variants.

Key Takeaways (Recap)

  • Structs: Use named fields for complex data, tuple structs for concise data.
  • Enums: Define multiple possible states, optionally carrying data.
  • Pattern Matching: Exhaustively handle cases, ensuring safety and clarity. Use guards for conditional matching.

Next Up: Traits and Generics

This tutorial has covered structs, enums, and pattern matching. The next step in learning Rust is to explore traits (which are like interfaces in other languages) and generics (which allow you to write code that works with different types). These features will allow you to write more reusable and flexible code.

Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin