Rust的模块系统可以使用它来管理不断增长的项目,并跟踪 modules
存储在何处。
Rust的模块系统是将代码组织成逻辑片段的有效工具,因此可以实现代码维护和重用。模块支持分层组织、隐私管理和代码封装。Rust为开发人员提供了多功能和可扩展的方法来管理项目复杂性,其功能包括use关键字,嵌套路径以及将模块划分为独立文件的能力。
Introduction 介绍
In Rust, the module system helps keep code organized by grouping related functions, types, and other items together, making it easier to manage and reuse code in a project.
在Rust中,模块系统通过将相关的函数、类型和其他项分组在一起来帮助组织代码,从而更容易在项目中管理和重用代码。
For example: 举例来说:
Let’s say a part of your code is working with managing the database, you don’t really want it to be accessed by an image renderer. So we store them in different locations, in different modules
假设你的一部分代码是用来管理数据库的,你并不真的希望它被图像渲染器访问。所以我们把它们存放在不同的地方,不同的 modules
We can use the use
keyword to access certain parts of a different modules
.
我们可以使用 use
关键字来访问不同 modules
的某些部分。
When we run the cargo new
command, we are technically creating a package and a package stores crates
. There are two types of crates
当我们运行 cargo new
命令时,我们在技术上创建了一个包和一个包存储 crates
。有两种板条箱
- Binary crate : Can be executed directly
Binary crate:可以直接执行- Library crate : Can be used by other programs/packages
Library crate:可以被其他程序/包使用
Each crate stores modules, That organize the code and control the privacy of your rust program.
每个箱子里都有模块,用来组织代码并控制生锈程序的隐私.
Let’s take a deeper look into it.
让我们深入了解一下。
Create a new package by running :
通过运行以下命令创建新包:
$ cargo new module_system
$ cd module_system
$ ls
Cargo.toml
src/
Reading the Cargo.toml
file we can see :
阅读 Cargo.toml
文件,我们可以看到:
[package]
name = "modu