Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Defining Modules in Rust

What are Modules?

In Rust, modules are a way to organize code into separate namespaces. They help to manage complexity by allowing you to group related functionalities together. This encapsulation allows for better code organization and can help avoid naming conflicts.

Creating a Module

To define a module in Rust, you use the mod keyword followed by the module name. You can define a module inline or in a separate file. Here is a simple example:

mod my_module {

pub fn greet() {

println!("Hello from my_module!");

}

}

In this example, we defined a module named my_module which contains a public function greet.

Using a Module

Once you've defined a module, you can use it by including it in your main function or another module. You can access the functions using the module_name::function_name syntax. Here is how to use the greet function from our my_module:

fn main() {

my_module::greet();

}

When you run this code, it will output:

Hello from my_module!

Module Files and Directories

In Rust, you can organize your modules across multiple files. If you want to define a module in a separate file, you need to create a file named module_name.rs or a directory named module_name containing a mod.rs file. For example, to define my_module in a separate file:

Create a file named my_module.rs:

// my_module.rs

pub fn greet() {

println!("Hello from my_module!");

}

Then, in your main file, you would include the module like this:

mod my_module;

fn main() {

my_module::greet();

}

Visibility of Modules

By default, modules are private. To make a module or its items public, you need to use the pub keyword. When you define a function or a struct inside a module, you must explicitly declare it as public if you want it to be accessible from outside the module.

mod my_module {

pub fn public_function() {

println!("This function is public!");

}

}

Conclusion

Modules in Rust are a powerful feature for organizing code into manageable sections. By grouping related functionalities, you can create more maintainable and understandable codebases. Remember to use the pub keyword when you want to expose functionality to other parts of your program.