Basics
Rust Modules
Using Rust Modules
Rust modules use mod and use for code organization.
Introduction to Rust Modules
In Rust, modules are a powerful feature that allows developers to organize code into logical units. This not only helps with code readability but also with reusability and encapsulation. The mod
keyword is used to declare a module, while the use
keyword is employed to bring module contents into scope. Let's delve into how these work in practice.
Declaring a Module with mod
To declare a module in Rust, you use the mod
keyword followed by the module name. This can be done within a file or across multiple files for better organization. Here's a simple example of declaring a module:
Using the use Keyword
Once you have a module, you'll often want to use its contents in other parts of your program. The use
keyword allows you to bring items from a module into scope, making them easier to reference. Here's how you can use the say_hello
function from my_module
:
Organizing Modules Across Files
For larger projects, it's common to split modules into separate files. Rust uses a directory structure to map files to modules. For instance, a module named network
can be defined in a file named network.rs
. If the module has submodules, they can be placed in a directory named network
with a mod.rs
file:
With this setup, you can use functions from the tcp
and udp
modules in your main program by specifying the module path:
Conclusion
Rust modules are an essential part of the language's structure, enabling better code organization and modular design. By using mod
and use
, you can create clear and maintainable codebases. As you build more complex projects, understanding and utilizing modules will be key to managing your code effectively.
Basics
- Previous
- Security Basics
- Next
- Crates