Separating modules into different files is a good way to manage growing Rust projects. It makes the code easier to navigate and maintain, and it allows you to group related code together.
To separate a module into a different file, you need to:
- Create a new file with the same name as the module, in a directory that matches the module's location in the module tree. For example, if the module is
front_of_house
, you would create a new file calledfront_of_house.rs
in thesrc/
directory. - Move the code for the module into the new file.
- Update the module declaration in the parent module to use the
mod
keyword. For example, if thefront_of_house
module is a child of the root module, you would update thesrc/lib.rs
file to contain the following line:
mod front_of_house;
Once you have done these steps, you will be able to access the module's code from other modules in your project using a path. For example, to call the add_to_waitlist()
function in the front_of_house
module, you would use the following code:
use crate::front_of_house::hosting;
fn main() {
hosting::add_to_waitlist();
}
Note: You only need to use the mod
keyword to declare a module once in your project. Once the compiler knows that a module exists, it will be able to find the code for that module in the appropriate file.
Example:
The following example shows how to separate the front_of_house
module into a different file:
// src/lib.rs
mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
// src/front_of_house.rs
pub mod hosting {
pub fn add_to_waitlist() {}
}
Benefits of separating modules into different files:
- Makes code easier to navigate and maintain: When modules are separated into different files, it is easier to find the code you are looking for and to understand how the different parts of your program fit together.
- Allows you to group related code together: Separating modules into different files allows you to group related code together, which can make your code more readable and maintainable.
- Improves performance: The Rust compiler can optimize code that is in different files more effectively than code that is in the same file.