学习Rust的第11天:模块系统

ops/2024/9/23 22:41:22/

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 。有两种板条箱

  1. Binary crate : Can be executed directly
    Binary crate:可以直接执行
  2. 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 :
通过运行以下命令创建新包:

rust">$ cargo new module_system
$ cd module_system
$ ls
Cargo.toml
src/

Reading the Cargo.toml file we can see :
阅读 Cargo.toml 文件,我们可以看到:

rust">[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
包装和板条箱规则

  1. A package must have atleast one crate.
    一个包必须至少有一个板条箱。
  2. A package can either contain 0 library crates or 1 library crate
    一个包可以包含0个库箱或1个库箱
  3. 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,我们可以使用以下命令

rust">cargo new --lib user
rust">//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 函数。我该怎么称呼它?

rust">//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 例如

rust">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.
这些规则有助于强制封装并防止意外访问模块的内部细节。

rust">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 关键字允许您将路径带入作用域,这样您就不必一遍又一遍地指定路径,让我们看看前面的示例。

rust">//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 嵌套路径

rust">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 语句:

rust">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 模块这样做。

rust">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:将所有函数复制到该文件,但保留模块声明

rust">//File : src/authentication.rs
pub fn create_account(){}
fn login(){}
fn forgot_password(){}
rust">//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…
这样做的目的是,编译器查找与模块名称同名的文件,并将所有函数和其他数据放入模块中。
我们也可以对父模块这样做.


http://www.ppmy.cn/ops/11795.html

相关文章

在ELF 1开发环境中使用Qt Creator进行远程调试

Qt Creator是一款跨平台集成开发环境(IDE),主要适用于支持Qt框架的各类应用程序开发。其内置的远程调试机制使得开发者能够在本地开发环境中对部署在远程设备上的代码进行调试,无需直接对远程设备进行操作。Qt Creator会通过网络连…

Kali Linux扩容(使用图形化界面)

因为今天在拉取vulhub中的镜像的时候报错空间不够,因为最开始只给了20GB的空间,所以现在需要扩容了,结合了一下网上的找到了简便的解决方法 1.首先虚拟机设置->磁盘->扩展 小插曲:在对虚拟机磁盘进行扩容以后,…

mysql download 2024

好久没在官网下载 mysql server 安装包。今天想下载发现: 我访问mysql官网的速度好慢啊。mysql server 的下载页面在哪里啊,一下两下找不到。 最后,慢慢悠悠终于找到了下载页面,如下: https://dev.mysql.com/downlo…

dremio支持设置

Dremio 支持提供可用于诊断目的的设置。这些设置通过 Dremio UI:设置>支持启用(或禁用) 使用 Client Tools 可以配置当用户查看数据集中的数据时,Dremio 项目的工具栏上显示哪些客户端应用程序按钮。用户可以通过单击相应的工具…

盲人导航设备制造:赋能独立出行,革新生活体验

作为资深记者,我有幸亲历了一场由盲人导航设备制造领域创新成果所驱动的独立出行体验。一款名为蝙蝠避障的导航辅助应用,以其实时避障功能与便捷的人体工学设计,彻底改变了视障人士的出行方式,使之更加安全、自由。 首先&#xf…

windows Webrtc +VS2019 (M124)下载编译以及调通测试demo

下载depot tools 设置梯子 git config --global http.proxy 127.0.0.1:10000 git config --global https.proxy 127.0.0.1:10000 下载 $ git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git 设置depot_tools目录为环境变量 下载webrtc # 设置系统代…

[笔试强训day04]

文章目录 WY22 Fibonacci数列NC242 单词搜索BC140 杨辉三角 WY22 Fibonacci数列 WY22 Fibonacci数列 #include<iostream> #include<cmath>using namespace std;int n;int main() {cin>>n;int a0,b1,c1;while(n>c){ab;bc;cab;}int ansmin(n-b,c-n);cout&l…

nvm使用指定镜像安装node和npm包

场景 使用nvm时&#xff0c;默认的安装源经常碰到找不到可用版本的问题&#xff0c;这时就需要指定镜像源。比如如果你在学习鸿蒙ArkTs项目的开发&#xff0c;就需要指定从华为官方镜像上安装指定版本的node和npm包 命令 以windows为例&#xff0c;以管理员身份运行cmd工具&…