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

本文详细介绍了Rust编程语言的模块系统,如何通过组织模块、使用`use`关键字、管理crates和隐私规则来提高代码的可维护性和重用性。涵盖了模块的结构、访问控制、函数调用以及如何将模块存储在单独文件中。
摘要由CSDN通过智能技术生成

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 :
通过运行以下命令创建新包:

$ cargo new module_system
$ cd module_system
$ ls
Cargo.toml
src/

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

[package]
name = "modu
  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老父亲的能量嘎嘣脆

感谢支持,共同成长

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值