Rust的模块化

Rust的模块化要从Rust的入口文件谈起。

Rust的程序的入口文件有两个

  1. 如果程序类型是可执行应用,入口文件是main.rs
  2. 如果程序类型是库,入口文件是lib.rs

入口文件中,必须声明本地模块,否则编译器在编译过程中,会报该模块不存在的错误。这个规则,在其它程序的编译中很少见。

怎么理解这个规则,我来举一个例子:

假设我们目录结构如下:

bash 复制代码
src/
  components/
    mod.rs
    table_component.rs
  models/
    mod.rs
    table_row.rs
  main.rs

依赖关系如下,即main.rs没有直接依赖table_row.rs

bash 复制代码
main.rs -> table_component.rs -> table_row.rs

现在来看看模块之间的引用代码。

main.rs对table_component.rs的依赖,对应的代码为

rust 复制代码
use components::table_component::TableComponent;

table_component.rs对table_row.rs的依赖,对应的代码为

rust 复制代码
use crate::models::table_row::TableRow;

上面的依赖代码都没毛病。在main.rs中"use components::table_component::TableComponent"这段代码告诉编译器,从模块的根部找components模块,因为components是一个文件夹,所以components目录下有一个mod.rs,然后在components文件夹下找table_component模块,最后在table_component模块中找到TableComponent。

因为table_component.rs中使用到了models中定义的TableRow,所以,这行代码也没有毛病:"use crate::models::table_row::TableRow"。这行代码告诉编译器从模块的根目录找models模块,然后在models模块中找table_row模块,最后在table_row中找到TableRow。

但是如果仅仅是这样,编译器就会马上送上模块找不到的错误。这种错误对于才接触到Rust的同学来说,可能很难发现,尤其是才从别的开发语言(比如Javascript)过来的同学。

bash 复制代码
 --> src/main.rs:4:5
use components::table_component::TableComponent;
     ^^^^^^^^^^ use of undeclared crate or module `components`

上面的错误里中有"undclared crate or module",这里其实就是在提醒我们这个components模块没有被声明。

很简单,就是在main.rs的头部加上下面的代码。

rust 复制代码
mod components;

OK,如果你再次编译代码,你会发现下面这个错误。

bash 复制代码
 --> src/components/table_component.rs:1:12

 use crate::models::table_row::TableRow;
            ^^^^^^ could not find `models` in the crate root

如果没有把模块声明的原则放心上,这个提示会让人发狂,因为无论你检查多少次,你都会发现你的文件路径src/models/table_row.rs和模块的查找路径是对应的啊,为什么就找不到呢?

如果这里的报错还是能像之前那样用"use of undeclared crate or module"就好理解多了。要解决这个问题,其实也是将"mod models;"这行代码添加到main.rs中。即:

main.rs

rust 复制代码
mod components;
mod models;

把握好这个原则,其它模块间的引用方式,例如super, self都好理解了。

相关推荐
free-elcmacom1 小时前
C++ 默认参数详解:用法、规则与避坑指南
开发语言·c++
奋斗中的小猩猩1 小时前
OpenClaw不安全,Rust写的ZeroClaw给出满意答案
安全·rust·openclaw·小龙虾
码云数智-大飞1 小时前
分布式事务解决方案全景指南:2PC、TCC、SAGA 与 Seata 实战
开发语言
娇娇yyyyyy1 小时前
QT编程(10): QLineEdit
开发语言·qt
Albert Edison1 小时前
【ProtoBuf 语法详解】Any 类型
服务器·开发语言·c++·protobuf
喵叔哟1 小时前
5. 【Blazor全栈开发实战指南】--Blazor组件基础
开发语言·javascript·ecmascript
海奥华22 小时前
Rust初步学习
开发语言·学习·rust
卢锡荣2 小时前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑
、BeYourself2 小时前
Scala 基础语法
开发语言·scala
AMoon丶2 小时前
C++模版-函数模版,类模版基础
java·linux·c语言·开发语言·jvm·c++·算法