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 = "module_system"
version = "0.1.0"
edition = "2021"[dependencies]
Due to the rust convention, We cannot really see any crates
we have in this file but we do have a main.rs
file. Which means that there is a binary crate named module_system
in our package by default.
由于rust约定,我们在这个文件中看不到任何 crates
,但我们确实有一个 main.rs
文件。这意味着在我们的包中默认有一个名为 module_system
的二进制crate。
The same convention is followed for library crates, if lib.rs
is present in out src
directory, It will automatically create a library crate named module_system.
对于库crate也遵循相同的约定,如果 lib.rs
存在于 src
目录中,则会自动创建一个名为 module_system.
的库crate
Rules of packages and crates
包装和板条箱规则
- A package must have atleast one crate.
一个包必须至少有一个板条箱。 - A package can either contain 0 library crates or 1 library crate
一个包可以包含0个库箱或1个库箱 - A package can have
n
numbers of binary crates.
一个包可以有n
个二进制板条箱。
Modules 模块
Modules are library crates, defined with the mod
keyword. They are used to structure a Rust application better, let’s take a look at an example to better understand it.
模块是用 mod
关键字定义的库箱。它们用于更好地构建Rust应用程序,让我们看一个例子来更好地理解它。
To create a library crate, we can use this command
要创建库crate,我们可以使用以下命令
cargo new --lib user
//File : src/lib.rsmod user{mod authentication{fn create_account(){}fn login(){}fn forgot_password(){}}mod edit_profile{fn change_username(){}fn chang_pfp(){}fn change_email(){}}
}
This is what a module would look like.
这就是模块的样子。
A module can have multiple modules inside of it, we can define, structs, enums, functions and more inside a module.
一个模块里面可以有多个模块,我们可以在一个模块里面定义,结构,枚举,函数等等。
This method helps a lot with managing and maintaining code-bases. In future if we had to change a certain something with the forgot_password
function. We would know exactly where to find it…
这种方法对管理和维护代码库有很大帮助。在未来,如果我们不得不改变某些东西与 forgot_password
功能。我们就知道在哪能找到它...
Calling functions from a module
从模块调用函数
Let’s say, I want to enroll a new user into my service, and need to use the create_account
function. How do I call it?
比如说,我想在我的服务中注册一个新用户,需要使用 create_account
函数。我该怎么称呼它?
//File : src/lib.rsmod user{pub mod authentication{pub fn create_account(){}fn login(){}fn forgot_password(){}}mod edit_profile{fn change_username(){}fn chang_pfp(){}fn change_email(){}}
}pub fn call_module_function(){//Absolute pathcrate::user::authentication::create_account();//Relative pathuser::authentication::create_account();
}
We added a pub
keyword for out authentication module and create account function, because by default it is private
and cannot be called, because of module privacy rules
我们为out authentication模块和create account函数添加了一个 pub
关键字,因为默认情况下它是 private
,由于模块隐私规则,它不能被调用
Relative path refers to accessing modules or items within the same module hierarchy without specifying the root, while absolute path refers to accessing them by specifying the root module or crate.
相对路径指的是在不指定根的情况下访问同一模块层次结构中的模块或项目,而绝对路径指的是通过指定根模块或crate来访问它们。
For reference, here is what the module hierarchy looks like…
作为参考,下面是模块层次结构的样子。
The super
keyword can also be used for relatively calling a function, super
allows us to reference the parent module…
关键字 super
也可以用于相对调用函数, super
允许我们引用父模块。
Example 例如
mod parent_module {pub fn parent_function() {println!("This is a function in the parent module.");}
}mod child_module {// Importing the `parent_function` from the parent module using `super`use super::parent_module;pub fn child_function() {println!("This is a function in the child module.");// Calling the parent function using `super`parent_module::parent_function();}
}fn main() {// Calling the child function which in turn calls the parent functionchild_module::child_function();
}
Module privacy rules 模块隐私规则
Modules have privacy rules that control which items (such as structs, functions, and variables) are visible or accessible from outside the module.
模块具有隐私规则,这些规则控制哪些项(如结构、函数和变量)可从模块外部看到或访问。
These rules help enforce encapsulation and prevent unintended access to internal details of a module.
这些规则有助于强制封装并防止意外访问模块的内部细节。
mod my_module {// Public structpub struct PublicStruct {pub public_field: u32,}// Private structstruct PrivateStruct {private_field: u32,}// Public function to create instances of `PrivateStruct`pub fn create_private_struct() -> PrivateStruct {PrivateStruct { private_field: 42 }}
}fn main() {// Creating an instance of PublicStruct is allowed from outside the modulelet public_instance = my_module::PublicStruct { public_field: 10 };println!("Public field of PublicStruct: {}", public_instance.public_field);// Creating an instance of PrivateStruct is not allowed from outside the module// let private_instance = my_module::PrivateStruct { private_field: 20 }; // This would give a compile-time error// Accessing the private field of PublicStruct is not allowed// println!("Private field of PublicStruct: {}", public_instance.private_field); // This would give a compile-time error// However, we can create and access instances of PrivateStruct using the provided public functionlet private_instance = my_module::create_private_struct();// println!("Private field of PrivateStruct: {}", private_instance.private_field); // This would give a compile-time error
}
- Rust’s module system allows for organizing code into logical units.
Rust的模块系统允许将代码组织成逻辑单元。 - Visibility and access control in Rust modules are enforced through privacy rules.
Rust模块中的可见性和访问控制通过隐私规则来实施。 - In Rust, items (such as structs, functions, and variables) can be marked as either public or private within a module.
在Rust中,项目(如结构、函数和变量)可以在模块中标记为public或private。 - Public items are accessible from outside the module, while private items are not.
公共项可以从模块外部访问,而私有项则不能。 - Public items are typically designated with the
pub
keyword, while private items are not explicitly marked.
公共项通常使用pub
关键字指定,而私有项不显式标记。 - Private items are only accessible within the module where they are defined, promoting encapsulation and hiding implementation details.
私有项只能在定义它们的模块中访问,从而促进了封装并隐藏了实现细节。 - The
pub
keyword is used to make items visible outside the module, allowing them to be used by other parts of the codebase.pub
关键字用于使项目在模块外部可见,允许代码库的其他部分使用它们。 - The
super
keyword in Rust allows access to items in the parent module, facilitating hierarchical organization and access control within a crate.
Rust中的super
关键字允许访问父模块中的项目,促进了crate中的分层组织和访问控制。
Use Keyword 使用关键字
use
keyword allows you to bring a path into scope, so that you dont have to specify a path over and over again, let’s take a look at our previous example.use
关键字允许您将路径带入作用域,这样您就不必一遍又一遍地指定路径,让我们看看前面的示例。
//File : src/lib.rsmod user{pub mod authentication{pub fn create_account(){}fn login(){}fn forgot_password(){}}mod edit_profile{fn change_username(){}fn chang_pfp(){}fn change_email(){}}
}//adding the module to our scope
use crate::user::authentication;pub fn call_module_function(){//Instead of these, we can call it directly.//crate::user::authentication::create_account();//user::authentication::create_account();authentication::create_account();
}
Nested paths 嵌套路径
mod outer_module {pub mod inner_module {pub fn inner_function() {println!("This is an inner function.");}pub struct InnerStruct {pub value: i32,}}
}use outer_module::inner_module::inner_function;
use outer_module::inner_moduel::InnerStruct;fn main() {// Calling the inner functioninner_function();// Creating an instance of InnerStructlet inner_struct_instance = InnerStruct { value: 42 };println!("Value of inner struct: {}", inner_struct_instance.value);
}
Notice how both the use
statements start with outer_module::inner_module::
请注意,两个 use
语句都以 outer_module::inner_module::
开头
We can nest the two use
statements by this:
我们可以这样嵌套两个 use
语句:
use outer_module::inner_module::{inner_function, InnerStruct};
Modules in separate files
单独文件中的模块
To keep better track of our project and structure it better, we can store different modules in separate files. Let’s do that to the authentication
module.
为了更好地跟踪我们的项目并更好地构建它,我们可以将不同的模块存储在单独的文件中。让我们对 authentication
模块这样做。
mod user{pub mod authentication{pub fn create_account(){}fn login(){}fn forgot_password(){}}mod edit_profile{fn change_username(){}fn chang_pfp(){}fn change_email(){}}
}
Step 1 : Create a file in the src/
directory with the same name as the module, in out case authentication.rs
第1步:在 src/
目录中创建一个与模块同名的文件,例如 authentication.rs
Step 2 : Copy all the functions to that file but keep the module declaration
步骤2:将所有函数复制到该文件,但保留模块声明
//File : src/authentication.rs
pub fn create_account(){}
fn login(){}
fn forgot_password(){}
//File : src/lib.rs
mod user{pub mod authentication; //change the curly brackets to a semicolonmod edit_profile{fn change_username(){}fn chang_pfp(){}fn change_email(){}}
}
What this does it, the compiler looks for the file with the same name as the module name and puts all the functions and other data in the module.We can also do this for parent modules as well…
这样做的目的是,编译器查找与模块名称同名的文件,并将所有函数和其他数据放入模块中。我们也可以对父模块这样做.