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:

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.