Yes, in Rust, the filename generally becomes the module name when you declare it using the mod keyword. This is part of Rust's module system and helps in organizing your code effectively.
How it Works
-
Filename as Module Name:
- When you declare
mod my_module; in main.rs, Rust expects to find a file named my_module.rs in the src directory or a directory named my_module containing a mod.rs file.
- The contents of this file will be included as the module named
my_module.
-
Example:
- When you create
src/my_module.rs and declare mod my_module; in main.rs, Rust links the module name my_module to the file src/my_module.rs.
- You then use functions or items in this module with the
my_module:: prefix.
Expanded Example with Submodules
If you want to go a step further and create submodules, you can create a directory for the module and add files into it.
Step 1: Directory Structure
Expand your project structure as follows:
my_project/
├── Cargo.toml
└── src
├── main.rs
└── my_module
├── mod.rs
└── utilities.rs
Step 2: Define the Top-Level Module and Submodule
Create or update the src/my_module/mod.rs file to declare its submodule:
// src/my_module/mod.rs
// Declare the submodule `utilities`
pub mod utilities;
// Optional: Add top-level module functions or items here
pub fn greet(name: &str) {
println!("Hello from my_module, {}!", name);
}
Create the src/my_module/utilities.rs file to define functions in the submodule:
// src/my_module/utilities.rs
// Define functions in the submodule
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
Step 3: Use the Module and Submodule in main.rs
Modify src/main.rs to include and use the nested module and submodules:
// src/main.rs
// Declare the top-level module
mod my_module;
fn main() {
// Use the top-level module function
my_module::greet("Alice");
// Use the utility functions from the submodule
let result = my_module::utilities::add(5, 3);
println!("5 + 3 = {}", result);
}
Step 4: Run Your Program
Run your program with Cargo:
cargo run
You should see the output:
Hello from my_module, Alice!
5 + 3 = 8
Summary
- Yes, the filename generally becomes the module name.
- You can further organize your code using submodules by creating directories and
mod.rs files inside those directories.
- This provides a clear, hierarchical structure for organizing your code, making it easier to maintain and navigate.