Chapter 5: Structuring Your Code

As your programs grow beyond simple scripts, you need ways to organize related data and functionality. This chapter covers Rust's powerful tools for structuring code: structs for grouping data, enums for variant types, pattern matching for control flow, Result and Option for safe error handling, and modules for code organization.

Why Structure Matters

Well-structured code is easier to understand, maintain, and extend. Rust provides zero-cost abstractions for organizing your code - the structure you add doesn't impact runtime performance, but dramatically improves code quality and developer experience.

5.1 Structs: Grouping Related Data

A struct lets you group related values under a single name. Think of it like creating your own custom data type that bundles multiple pieces of information together:

struct User {
    username: String,
    email: String,
    active: bool,
    sign_in_count: u64,
}

fn main() {
    // Create an instance with all fields specified
    let user1 = User {
        email: String::from("user@example.com"),
        username: String::from("rustacean"),
        active: true,
        sign_in_count: 1,
    };

    // Access fields using dot notation
    println!("Welcome, {}!", user1.username);
    println!("Email: {}", user1.email);
}

Mutable Structs

To modify a struct's fields after creation, the entire instance must be mutable:

let mut user1 = User {
    email: String::from("old@example.com"),
    username: String::from("rustacean"),
    active: true,
    sign_in_count: 1,
};

// Now we can modify fields
user1.email = String::from("new@example.com");
user1.sign_in_count += 1;
All or Nothing Mutability

Rust doesn't allow marking individual fields as mutable. The entire struct instance is either mutable or immutable. This prevents the confusion of partial mutability and makes it clear who can modify the data.

Field Init Shorthand

When variable names match field names, you can use shorthand syntax:

fn build_user(email: String, username: String) -> User {
    User {
        email,         // Shorthand for email: email
        username,      // Shorthand for username: username
        active: true,
        sign_in_count: 1,
    }
}

Struct Update Syntax

Create a new instance based on an existing one, changing only some fields:

let user2 = User {
    email: String::from("another@example.com"),
    ..user1  // Use remaining fields from user1
};

// Note: user1.username was moved to user2
// user1 cannot be used for fields that were moved
Ownership with Struct Update

The .. syntax moves data. If you use it with String fields, the original struct becomes partially moved. Fields that implement Copy (like integers and booleans) are copied, not moved.

Tuple Structs and Unit Structs

// Tuple structs - named tuples with type distinction
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
// black and origin are different types!

// Access by index
println!("Red component: {}", black.0);

// Unit struct - no fields, useful for traits
struct AlwaysEqual;
let subject = AlwaysEqual;

5.2 Methods with impl

Add behavior to structs with impl (implementation) blocks. Methods are functions defined within the context of a struct:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // Method: takes &self as first parameter
    fn area(&self) -> u32 {
        self.width * self.height
    }

    // Method that checks another Rectangle
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }

    // Method with mutable self
    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }

    // Associated function: no self (like static method)
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }

    // Another associated function - constructor pattern
    fn new(width: u32, height: u32) -> Rectangle {
        Rectangle { width, height }
    }
}

fn main() {
    let rect = Rectangle::new(30, 50);
    println!("Area: {} square pixels", rect.area());

    let small = Rectangle::new(10, 20);
    println!("Can hold small? {}", rect.can_hold(&small));

    let square = Rectangle::square(10);  // Call associated function
    println!("Square area: {}", square.area());
}
Self Type Meaning Use Case
&self Immutable borrow of self Read data only, most common
&mut self Mutable borrow of self Modify data in place
self Take ownership of self Transform or consume the instance
Multiple impl Blocks

You can have multiple impl blocks for the same struct. This is useful when implementing traits or organizing related methods together.

5.3 Enums: Types with Variants

Enums define a type that can be one of several variants. Unlike C-style enums, Rust enums can hold data:

enum IpAddrKind {
    V4,
    V6,
}

let four = IpAddrKind::V4;
let six = IpAddrKind::V6;

// Use in function parameters
fn route(ip_kind: IpAddrKind) {
    // Handle routing based on IP type
}

Enums with Data

Each variant can hold different types and amounts of data - this is what makes Rust enums powerful:

enum Message {
    Quit,                           // No data
    Move { x: i32, y: i32 },       // Named fields (like a struct)
    Write(String),                  // Single value
    ChangeColor(i32, i32, i32),    // Multiple values (tuple-like)
}

// Each variant is its own type of Message
let msg1 = Message::Quit;
let msg2 = Message::Move { x: 10, y: 20 };
let msg3 = Message::Write(String::from("hello"));
let msg4 = Message::ChangeColor(255, 128, 0);

// Enums can have methods too!
impl Message {
    fn call(&self) {
        // Method body would go here
        println!("Message received!");
    }
}

msg3.call();
Enums vs Structs

Use structs when you always need all fields together. Use enums when a value could be one of several different things. For example, a network packet could be TCP or UDP - use an enum. A user always has a name and email - use a struct.

5.4 Option: No More Null

Rust has no null. Instead, it uses the Option enum to represent values that might be absent:

enum Option<T> {
    Some(T),   // There is a value of type T
    None,      // There is no value
}
// Option is so common it's included in the prelude
let some_number: Option<i32> = Some(5);
let some_string: Option<String> = Some(String::from("hello"));
let absent_number: Option<i32> = None;

// You can't use Option<T> as T directly
let x: i32 = 5;
let y: Option<i32> = Some(5);
// let sum = x + y;  // ERROR! Different types

// You must explicitly handle the Option
let sum = x + y.unwrap_or(0);  // Use default if None

Working with Option

let maybe_number: Option<i32> = Some(42);

// Common methods
maybe_number.is_some();              // true
maybe_number.is_none();              // false
maybe_number.unwrap();               // 42 (panics if None!)
maybe_number.unwrap_or(0);           // 42 (or default)
maybe_number.unwrap_or_default();    // Uses Default trait

// Transform with map
let doubled = maybe_number.map(|x| x * 2);  // Some(84)

// Chain with and_then
let result = maybe_number
    .map(|x| x * 2)
    .and_then(|x| if x > 50 { Some(x) } else { None });
Why Option is Better Than Null

With null, you might forget to check. With Option, the type system forces you to handle the None case. You literally can't use the value without acknowledging it might be absent. This eliminates null pointer exceptions at compile time.

5.5 Pattern Matching with match

The match expression is Rust's powerful control flow for handling patterns. It must be exhaustive - every possible case must be handled:

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => {
            println!("Lucky penny!");
            1
        }
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

Matching with Option

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

let five = Some(5);
let six = plus_one(five);   // Some(6)
let none = plus_one(None);  // None

Pattern Matching Features

// Catch-all pattern with _
let dice_roll = 7;
match dice_roll {
    3 => add_fancy_hat(),
    7 => remove_player_hat(),
    _ => reroll(),  // Matches anything else
}

// Binding values in patterns
enum UsState { Alabama, Alaska, /* ... */ }
enum Coin { Quarter(UsState), /* ... */ }

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Quarter(state) => {
            println!("State quarter from {:?}!", state);
            25
        }
        // ... other arms
    }
}

// Concise matching with if let
let some_value = Some(3);
if let Some(3) = some_value {
    println!("three!");
}

// With else
if let Some(max) = config_max {
    println!("Max is {}", max);
} else {
    println!("No max configured");
}

5.6 Result: Error Handling

Like Option, Result is an enum for handling operations that can fail:

enum Result<T, E> {
    Ok(T),    // Success with value T
    Err(E),   // Error with error type E
}

use std::fs::File;
use std::io::{self, Read};

fn main() {
    let file = File::open("hello.txt");

    let file = match file {
        Ok(file) => file,
        Err(error) => {
            panic!("Problem opening file: {:?}", error);
        }
    };
}

Matching Different Errors

use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let file = File::open("hello.txt");

    let file = match file {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating file: {:?}", e),
            },
            other_error => {
                panic!("Problem opening file: {:?}", other_error);
            }
        },
    };
}

The ? Operator

The ? operator provides concise error propagation:

fn read_username_from_file() -> Result<String, io::Error> {
    let mut file = File::open("hello.txt")?;  // Returns Err if fails
    let mut username = String::new();
    file.read_to_string(&mut username)?;      // Returns Err if fails
    Ok(username)
}

// Even shorter with chaining
fn read_username_short() -> Result<String, io::Error> {
    let mut username = String::new();
    File::open("hello.txt")?.read_to_string(&mut username)?;
    Ok(username)
}

// Shortest: using fs::read_to_string
fn read_username_shortest() -> Result<String, io::Error> {
    std::fs::read_to_string("hello.txt")
}
Where ? Can Be Used

The ? operator can only be used in functions that return Result or Option. In main(), you can change the signature to fn main() -> Result<(), Box<dyn Error>> to use ?.

5.7 Modules: Organizing Code

Modules help organize code into logical units with visibility control:

// Define modules inline
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
        fn seat_at_table() {}  // Private
    }

    mod serving {  // Private module
        fn take_order() {}
        fn serve_order() {}
    }
}

// Use paths to access module items
use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();

    // With use statement
    hosting::add_to_waitlist();
}

File-Based Modules

// src/lib.rs or src/main.rs
mod front_of_house;  // Loads from src/front_of_house.rs
                     // or src/front_of_house/mod.rs

// src/front_of_house.rs
pub mod hosting;  // Loads from src/front_of_house/hosting.rs

// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}
Visibility Meaning
(default) Private to current module and children
pub Public to parent modules
pub(crate) Public within the current crate only
pub(super) Public to parent module only

5.8 Chapter Summary

Key Takeaways

5.9 Review Questions

Test Your Understanding

  1. What's the difference between a struct method (with &self) and an associated function (no self)? When would you use each?
  2. How do enums in Rust differ from enums in languages like C or Java? What additional capabilities do Rust enums provide?
  3. Why does Rust use Option instead of null? What specific class of bugs does this eliminate?
  4. What does "exhaustive matching" mean in the context of match expressions? Why is it important for code correctness?
  5. Explain the difference between &self, &mut self, and self in method signatures. Provide a use case for each.
  6. How does the ? operator work with Result types? What happens when it encounters an Err value?

5.10 Looking Ahead

What's Next: Chapter 6 - Advanced Features

Build on your foundation with Rust's powerful abstractions for code reuse and flexibility: