[Avg. reading time: 7 minutes]
Rust Modules
As Rust programs grow larger, organizing code becomes important.
Rust provides a module system to organize code into logical groups.
A module is a container that groups related items together.
These items can include:
- Functions
- Structs
- Enums
- Constants
- Traits
- Other modules
Modules help with:
- Organizing large codebases
- Controlling visibility of code
- Avoiding name conflicts
- Making programs easier to maintain
Example Concept
In small programs everything may live inside one file. As the project grows, it becomes difficult to maintain. Instead of putting everything in one file, Rust allows code to be split into modules.
Example project structure:
project
├── main.rs
├── user.rs
├── database.rs
Each file can represent a logical part of the program.
For example:
user.rs: user related logicdatabase.rs: database operations
This makes the program easier to read and maintain.
Standard Library Modules
Rust includes a large Standard Library (std) which contains many commonly used modules.
These modules provide functionality such as:
- Input and Output
- File handling
- Networking
- Data structures
- Memory management
Example standard module: std::io
The std::io module contains functionality for reading and writing input/output.
Using a Module
To access items from a module, Rust uses the use keyword.
Example:
use std::fs::File; fn main() { let file = File::create("data.txt").unwrap(); }
std → Standard Library
fs → Filesystem module
File → Struct used for file operations
Module Paths
Rust accesses modules using a path, similar to directories in a file system.
Example path:
std::fs::File
This represents the hierarchy:
Standard Library → Filesystem Module → File Struct
Using module paths helps Rust locate items within the module system.
Example
use std::io;
fn main() {
println!("Enter your name:");
let mut name = String::new();
io::stdin()
.read_line(&mut name)
.expect("Failed to read input");
println!("Hello {}", name.trim());
}
Standard Library Documentation
Rust provides detailed documentation for all standard modules.
You can explore them here:
https://doc.rust-lang.org/std/
https://doc.rust-lang.org/std/io/index.html
These pages list all modules, functions, and structs available in the standard library.