In Rust, a module is a namespace that contains code definitions and declarations. It is used to group related code together, making it easy to organize and maintain large codebases.
A module can contain functions, structs, enums, constants, types, other modules, and more. In order to define a module, you need to use the ‘mod‘ keyword followed by a block of code.
Here’s an example of how to define a simple module:
mod my_module {
fn hello() {
println!("Hello, world!");
}
}
In this example, we’ve defined a module called ‘my_module‘ that contains a single function named ‘hello‘. Note that the ‘fn‘ keyword is used to define a function inside a module, just like it is used to define a function outside of a module.
You can also nest modules inside other modules to create a hierarchy:
mod my_module {
mod nested_module {
fn hello() {
println!("Hello, nested world!");
}
}
}
In this example, we’ve defined a module called ‘my_module‘ that contains another module called ‘nested_module‘. ‘nested_module‘ contains a single function named ‘hello‘.
To use the code inside a module, you need to use the ‘use‘ keyword to bring the module’s code into your current scope. Here’s an example:
mod my_module {
pub fn hello() {
println!("Hello, world!");
}
}
fn main() {
my_module::hello();
}
In this example, we’ve defined a module called ‘my_module‘ that contains a function named ‘hello‘. We’ve marked the function as ‘pub‘ so that it can be used outside of the module. In our ‘main‘ function, we’ve used the ‘use‘ keyword to bring the ‘my_module‘ module into our scope, so that we can call the ‘hello‘ function.