crate

Let’s start with the official definition.

A crate is a binary or library. The crate root is a source file that the Rust compiler starts from and makes up the root module of your crate (we’ll explain modules in depth in the “Defining Modules to Control Scope and Privacy” section). A package is one or more crates that provide a set of functionality. A package contains a Cargo.toml file that describes how to build those crates.

A crate is the smallest compilation unit in rust, which means that rust is compiled one crate at a time, and each crate has an entry file, which can be one of the following three cases.

  • the main.rs file under src
  • the lib.rs file under src (as a library)
  • any file in the src/bin directory (containing the main function)

mod

A mod, on the other hand, is more like a namespace in C++ and can be used as a root mod in the following cases.

  • A single file as a mod
  • a folder containing mod.rs (other files are declared as submods in mod.rs)
  • a file of the same name rs at the same level of the folder

A mod is nestable, it is a tree structure, to use a mod, the mod must be declared in one of the entry files (actually rust is looking for the file to be replaced with this mod name), while a child mod can be declared in its parent mod, and then there are several ways to use it where it is to be used, as follows.

  • If the mod is declared in this file, the mod can be used directly.
  • using the use keyword to introduce mods declared in other files.
  • To use a mod under the same crate in the src/bin directory, you need to: declare it in lib.rs, and then use the name of this crate as the path to use.
  • In src/main.rs the previous way can be used, but it is also possible to leave out lib.rs and declare mods directly in this file.
  • All declared mods need to be pub exported if they are used in other files.
  • use is just to simplify the path, or you can write directly from the root mod all the way down without using the use keyword.

Example

File directory structure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
├─src
│  │  lib.rs
│  │  main.rs
│  │
│  ├─bin
│  │      test.rs
│  │
│  └─test_mod
│          child.rs
│          mod.rs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// test_mod/child.rs
pub fn test(){
    println!("hello,world")
}
// test_mod/mod.rs
pub mod child; // 导出子mod
// lib.rs
pub mod test_mod; // 将本crate声明为一个库
// main.rs
mod test_mod;
fn main() {
    test_mod:🧒:test();
}
// 或者直接:
fn main() {
    crate_mod::test_mod:🧒:test()
}
// bin/test.rs
use crate_mod::test_mod::child;
fn main() {
    child::test()
}