2.7 Modules and Crates
2.7.1 Modules
Rust uses modules to organize code, replacing the header-file system in C.
Defining Modules
mod my_module {
pub fn my_function() {
println!("This is my function");
}
}
- Use
mod
to define a module. - Use
pub
to make items public.
Using Modules
mod my_module { pub fn my_function() { println!("This is my function"); } } fn main() { my_module::my_function(); }
2.7.2 Splitting Modules Across Files
- Create a file named
my_module.rs
. - In your main file, declare:
mod my_module;
Now, my_module
is available in your code.
2.7.3 Crates
- A crate is a compilation unit in Rust (like a library or executable).
- Crates can be binary (with a
main
function) or library crates.
2.7.4 Comparison with C
- C uses header files (
.h
) and source files (.c
). - Headers declare functions and variables; source files define them.
// my_module.h
void my_function();
// my_module.c
#include "my_module.h"
#include <stdio.h>
void my_function() {
printf("This is my function\n");
}
// main.c
#include "my_module.h"
int main() {
my_function();
return 0;
}