The Magic of Code Organization
Ever felt like your Rust code is turning into spaghetti? That’s where modules and crates come in! They help you keep things neat, organized, and scalable. Let’s dive in!
1. What is a Module?
A module is a way to group related functionality together. Think of it as a folder for your code!
a) Defining a Module
mod greetings {
pub fn hello() {
println!("Hello from a module!");
}
}
fn main() {
greetings::hello();
}
Use mod
to define a module. pub
makes functions accessible from outside the module. Call it using module_name::function_name()
.
2. Nested Modules
Modules can be nested to organize code further!
mod company {
pub mod department {
pub fn work() {
println!("Working in the Rust department!");
}
}
}
fn main() {
company::department::work();
}
Use mod
inside mod
to nest modules. Call nested modules using parent::child::function()
.
3. What is a Crate?
A crate is the smallest unit of Rust compilation. It can be:
- A binary crate (an executable program).
- A library crate (a reusable library).
a) Using External Crates
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let num: u8 = rng.gen_range(1..=10);
println!("Random number: {}", num);
}
Add dependencies in Cargo.toml
:
[dependencies]
rand = "0.8"
Use use
to bring crate functions into scope.
4. Creating Your Own Crate
Want to make your own Rust library? Easy!
- Run
cargo new my_library --lib
- Define modules in
src/lib.rs
- Publish to crates.io!
Wrapping Up
Now you know: Modules organize your code. Nested modules make it even neater. Crates allow code reuse. External crates supercharge Rust programs.
Keep your Rust code clean and modular!
0 Comments