Lv777

Lv777

github
twitter
jike
playstation
xiaoyuzhou

Modules

package#

A package is a collection of one or more crates. A Cargo project is a package.

A package can contain one or more binary items, but only one library. Why is that? Is it for publishing reasons? To create other binary items, simply place the files in the src/bin directory and they will be compiled into separate binary files.

crate#

A crate is divided into binary items and libraries. The default template created by Cargo only includes one binary item, with src/main.rs conventionally being the root file. Cargo also conventionally designates src/lib.rs as the root file for libraries.

Compiling a crate starts by searching for the required code from the root file.

mod#

mod is used to group the code of a crate, and can also create submodules for modules. The code in a module is private by default.

mod web {
	mod client {
		mod home {}
		fn get_env() {}
	}
	mod server {
		struct DTO {
			id: String
		}
	}
}

Paths#

  • Absolute paths are full paths that start with the crate name (use crate for the same crate).
  • Relative paths are paths that start from the current module and use self, super, and the module name to locate.

use#

Use the use keyword to import a module that can be accessed, allowing you to directly use the contents of that module's scope, similar to import in JavaScript.

  • For function imports, it is common to import the parent module and specify it when calling, similar to call(this).
  • For structs, enums, etc., it is common to import the complete path and use them directly.
use web::client;

use web::server::DTO;

client.get_env();

DTO {
	id: String::from(""),
};
// Re-exporting
pub use web::server;
// Nested import
use web::{self, server::DTO};
// Import all public submodules of web
use web::*;

Module files#

Splitting a large module into multiple files is more conducive to readability, similar to the idea of modularization in frontend development.

web
├── client
│	└── home.rs
└── server.rs
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.