Skip to main content

Relationship Between Package, Crate, and Mod in Rust

1. Relationship Between Package and Crate​

If your previous language was Java, you'd better forget Java's corresponding relationships. In Rust, package can refer to either a project or a dependency.

If you want to map it to Java: package = project or dependency (in Java)

This unconventional naming is quite confusing.

2. Relationship Between Crate and Mod​

A crate can have multiple modules, and modules can contain other modules.

Starting from a simple example, mod written in main.rs:

mod system_config{
pub mod load_config_from_resource{
pub fn load(){
println!("this config load from resource file");
}
}

pub mod load_config_from_internet{
pub fn load(){
println!("this config load from internet");
}
}

}

fn main() {
system_config::load_config_from_resource::load();
system_config::load_config_from_internet::load();
}

This code is executable, and the result is:

We can also write the call like this - note that the structure starting from main is crate:

fn main() {
crate::system_config::load_config_from_resource::load();
crate::system_config::load_config_from_internet::load();
}

If we also add a load method in mod system_config, that's possible too:


mod system_config{
pub mod load_config_from_resource{
pub fn load(){
println!("this config load from resource file");
}
}

pub mod load_config_from_internet{
pub fn load(){
println!("this config load from internet");
}
}

pub fn load(){
println!("this config load by default function");
}

}

fn main() {
crate::system_config::load_config_from_resource::load();
crate::system_config::load_config_from_internet::load();
crate::system_config::load();
}

The execution result is:

Then we split the mod into other files.

I created a folder in the project root directory, then created a mod.rs file inside (it must be named this). The project structure looks like this:

project-name:
src:
config:
mod.rs
resources
main.rs

The call in main.rs is now:

mod config;

fn main() {
config::system_config::load_config_from_resource::load();
config::system_config::load_config_from_internet::load();
config::system_config::load();
}

You may notice the reference in main.rs is mod config, because Rust defaults to using the folder name and requires a mod.rs file to exist in the folder.