| In Rust, you can load and use modules defined in external files by following these steps: 1. Create a File StructureRust organizes modules based on file and directory structure. For example: src/
├── main.rs
├── utils.rs
2. Define a Module in the External FileCreate utils.rs and define your module: // utils.rs
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
3. Load the Module in main.rsIn your main.rs, use the mod keyword to declare the module and bring it into scope: // main.rs
mod utils;
fn main() {
utils::greet("Alice");
}
4. Using Submodules (Optional)If you want to organize your code into submodules within a directory, the structure looks like this: src/
├── main.rs
├── utils/
│ ├── mod.rs
│ └── math.rs
Define Submodule in mod.rs// utils/mod.rs
pub mod math;
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
Define Functionality in math.rs// utils/math.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
Load and Use Submodules in main.rs// main.rs
mod utils;
fn main() {
utils::greet("Alice");
let sum = utils::math::add(3, 4);
println!("Sum: {}", sum);
}
Key Points- File Naming and Structure: Rust modules correspond to file and directory names.
mod utils; looks for utils.rs or utils/mod.rs in the same directory.
pub Keyword: Functions and modules must be declared pub to make them accessible from outside their defining module.- Cargo: Ensure your files are in the
src directory if using Cargo for project management.
This approach allows you to split and organize your Rust code across multiple files while maintaining modularity and clarity. |