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.
|
|