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

Today we are taking a look at the module system of rust. We can use this to manage growing projects and keep track of what modules is stored where…
今天我们来看看Rust的模块系统。我们可以使用它来管理不断增长的项目,并跟踪 modules 存储在何处。

Rust’s module system is an effective tool for organizing code into logical pieces, hence enabling code maintenance and reuse. Modules support hierarchical organization, privacy management, and code encapsulation. Rust offers developers versatile and scalable methods for managing project complexity with features such as the use keyword, nested paths, and the ability to divide modules into independent files.
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 :
通过运行以下命令创建新包:

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

  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,我们可以使用以下命令

cargo new --lib user
//File : src/lib.rs

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

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(){}
  }
}

pub fn call_module_function(){
  //Absolute path
  crate::user::authentication::create_account();

  //Relative path
  user::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 function
    child_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 struct
    pub struct PublicStruct {
        pub public_field: u32,
    }

    // Private struct
    struct 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 module
    let 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 function
    let 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.rs

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(){}
  }
}

//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 function
    inner_function();

    // Creating an instance of InnerStruct
    let 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 semicolon

  mod 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.mfbz.cn/a/559214.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MyBatis使用PageHelper分页插件

1、不使用PageHelper分页插件 模块名:mybatis-012-page CarMapper接口package org.example.mapper;import org.apache.ibatis.annotations.Param; import org.example.pojo.Car;import java.util.List;public interface CarMapper {/*** 分页查询* param startInd…

LLMs之Llama3:Llama 3的简介、安装和使用方法、案例应用之详细攻略

LLMs之Llama3:Llama 3的简介、安装和使用方法、案例应用之详细攻略 导读:2024年4月18日,Meta 重磅推出了Meta Llama 3,本文章主要介绍了Meta推出的新的开源大语言模型Meta Llama 3。模型架构 Llama 3 是一种自回归语言模型&#x…

1000w背后的故事!

如果只让提一个合作中不靠谱的事,我想说,只要说钱不是问题的,都不靠谱。 因为我经历过的,钱不是问题也有顺利合作的,但绝大多数都是出现在钱的问题上。 我现在最怕就是熟人找来做项目,说多钱你说&#xff0…

在jsp里或servlet里将时间修改为类似“2023年 8月 03日 时间:23:13:49 星期四”形式

jsp 例如&#xff0c;从数据库读到的EL表达式的时间形式为Thu Aug 03 23:13:49 CST 2023 在jsp这边用<script>将获得的EL表达式修改为类似“2023年 8月 03日 时间:23:13:49 星期四”形式展现在网页上 <c:forEach items"${sessionScope.SecurityManagementlist}…

ubuntu18.04安装F4PGA教程

环境搭建教程&#xff1a; f4pga-arch-defs/xilinx/xc7 at main f4pga/f4pga-arch-defs GitHub git clone https://github.com/SymbiFlow/f4pga-arch-defs.git cd f4pga-arch-defs make env cd build 主要是make env&#xff0c;会下载很多东西&#xff0c;然后生成很多描…

前端开发与html学习笔记

一、前端开发概述 前端开发&#xff1a;也叫做web前端开发&#xff0c;它指的是基于web的互联网产品的页面(也可叫界面)开发及功能开发互联网产品&#xff1a;指网站为满足用户需求而创建的用于运营的功能及服务&#xff0c;百度搜索、淘宝、QQ、微博、网易邮箱等都是互联网产…

3.2 iHRM人力资源 - 组织架构 - 编辑及删除

iHRM人力资源 - 组织架构 文章目录 iHRM人力资源 - 组织架构一、编辑功能1.1 表单弹层并数据回显1.2 编辑校验1.3 编辑 二、删除功能 一、编辑功能 编辑功能和新增功能用的组件其实是一个&#xff0c;结构几乎是一样的&#xff0c;其实是复用了组件&#xff0c;我们也省去了很…

(十六)call、apply、bind介绍、区别和实现

函数中的this指向&#xff1a; 函数中的this指向是在函数被调用的时候确定的&#xff0c;也就是执行上下文被创建时确定的。在一个执行上下文中&#xff0c;this由调用者提供&#xff0c;由调用函数的方式来决定。 类数组对象arguments&#xff1a; arguments只在函数&#…

二叉检索树 及 插入方法的图解、实现、时间代价分析

1、二叉检索树&#xff1a; &#xff08;1&#xff09;定义 二叉检索树的任意一个结点&#xff0c;设其值为k&#xff0c;则该节点左子树中任意一个结点的值都小于k&#xff1b;该节点右子树中任意一个节点的值都大于或等于k 这里的比较规则可以是针对数字的&#xff0c;也可…

工程上有哪些实用且简单的滤波方法?

一、工程滤波 在工程实践过程中&#xff0c;以下是一些常用的滤波方法及其优缺点&#xff1a; 限幅滤波 优点&#xff1a;简单易行&#xff0c;能够有效去除突变的大噪声&#xff0c;保护后续电路和传感器不受损伤。 缺点&#xff1a;可能会丢失信号的真实峰值&#xff0c;对真…

有关栈的练习

栈练习1 给定一个栈&#xff08;初始为空&#xff0c;元素类型为整数&#xff0c;且小于等于 109&#xff09;&#xff0c;只有两个操作&#xff1a;入栈和出栈。先给出这些操作&#xff0c;请输出最终栈的栈顶元素。 操作解释&#xff1a; 1 表示将一个数据元素入栈&#xff…

平衡二叉树(后序遍历,力扣110)

解题思路&#xff1a;采取后序遍历的好处是先遍历节点得到高度&#xff0c;然后再判断高度差是否大于一&#xff0c;如果是的话就返回-1&#xff0c;不是就返回两高度中较大的高度加一就是父节点的高度 具体代码如下&#xff1a; class Solution { public: int travel(TreeN…

antDesign Form表单校验(react)

<script><Form name"basic" ref{formRef} onFinish{onFinish}><Form.Itemlabel校验name"check"rules{[// 校验必填{required: true,message: 请输入&#xff01;},// 校验输入字符数限制{validator: (_, value) >value && value…

TCP三次握手,但通俗理解

如何用通俗的语言来解释TCP&#xff08;传输控制协议&#xff09;的三次握手过程&#xff1f; 想象一下你正在和朋友电话沟通&#xff0c;但你们之间不是心灵感应&#xff0c;而是需要通过清晰地听到对方的声音来确认通话质量良好。TCP三次握手就像是在电话拨通之前&#xff0…

OMNeT++与无线通信网络仿真——第二部分INET框架介绍 阅读笔记

13.5 熟悉INET框架 INET框架建立在Omnet基础上&#xff0c;并且使用相同的概念&#xff0c;即模块通过消息传递通信。 主机、路由器、交换机和其他网络设备有OMNeT复合模块表示。这些复合模块由表示协议、应用和其他功能单元的简单模块组成。网络又是一次包含主机、路由器和其…

怎么把网页上的文字变小?

以下是针对常见浏览器的说明&#xff1a; ### Google Chrome&#xff1a; 1. 打开 Chrome 浏览器并导航到您想要调整文字大小的网页。 2. 在页面上右键单击空白处&#xff0c;然后选择 "检查" 或按下 CtrlShiftI&#xff08;在 Windows 或 Linux 上&#xff09;或 Co…

混合现实(MR)开发框架

混合现实&#xff08;MR&#xff09;开发框架为开发者提供了构建MR应用程序所需的基本工具和功能。它们通常包括3D引擎、场景图、输入系统、音频系统、网络功能以及支持同时处理现实世界和虚拟世界信息的功能。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&…

java-springmvc 01

MVC就是和Tomcat有关。 01.MVC启动的第一步&#xff0c;启动Tomcat 02.Tomcat会解析web-inf的web.xml文件

java-spring 图灵 04 doscan方法,重点是scanCandidateComponents方法

01.本次的重点依旧是扫描函数&#xff0c;这次是spring中的源码&#xff1a; 02.第一步&#xff0c;构造AnnotationConfigApplicationContext 主方法&#xff1a; public static void main(String[] args) {// 创建一个Spring容器AnnotationConfigApplicationContext applica…

我们一起看看《看漫画学C++》中如何讲解对象的动态创建与销毁

《看漫画学C》这本书中会用图文的方式生动地解释对象的动态创建与销毁。在C中&#xff0c;动态创建对象是通过new运算符来实现的&#xff0c;而销毁对象则是通过delete运算符来完成的。这种方式可以让程序在需要时分配内存给对象&#xff0c;并在对象不再需要时释放内存&#x…
最新文章