Menu
Coddy logo textTech

Modules Basics

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 8 of 61.

As your Rust programs grow, keeping everything in a single file becomes unwieldy. Rust's module system lets you organize code by moving structs and their implementations into separate files.

To create a module in a separate file, you simply create a new file with your desired module name. For example, to create a player module, you'd create a file called player.rs:

// player.rs
struct Player {
    name: String,
    score: u32,
}

impl Player {
    fn new(name: String) -> Player {
        Player { name, score: 0 }
    }
}

To use this module in your main file, you declare it with the mod keyword. This tells Rust to look for a file with that name:

// main.rs
mod player;

fn main() {
    // We can now access items from the player module
}

The mod player; declaration tells Rust to find and include the contents of player.rs. Think of it as linking that file's code into your program. The module name must match the filename exactly (without the .rs extension).

This separation keeps related code together—your struct definition and all its methods live in one dedicated file, while main.rs stays focused on the program's entry point. In the next lesson, you'll learn how to actually access the items you've placed in modules.

Cheat sheet

To organize code into separate files, create a module file with the desired name. For example, player.rs:

// player.rs
struct Player {
    name: String,
    score: u32,
}

impl Player {
    fn new(name: String) -> Player {
        Player { name, score: 0 }
    }
}

To use the module in your main file, declare it with the mod keyword:

// main.rs
mod player;

fn main() {
    // Module contents are now available
}

The mod player; declaration tells Rust to find and include player.rs. The module name must match the filename exactly (without the .rs extension).

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming