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都好理解了。

相关推荐
hy.z_7773 分钟前
【C++】9. Vector
开发语言·c++
Tim_1030 分钟前
【C++】023、移动语义&深拷贝
开发语言·c++·算法
ctlover37 分钟前
Python模块与包
开发语言·python
雨田言炎39 分钟前
十、QThread多线程
linux·服务器·开发语言·前端·qt
djjjx.1 小时前
【 C++ 】stack、queue、优先级队列、仿函数、容器适配器
开发语言·c++
在世修行1 小时前
从零打造 C# 工业视觉检测系统(十一):Task 异步编程与实时性保障
开发语言·c#·task异步
程序员爱钓鱼1 小时前
Rust 可变借用详解:&mut T 与安全修改数据
后端·面试·rust
BUG研究员_11 小时前
Runnable与LCEL
开发语言·人工智能·python
牛艺翔13 小时前
C++基础
开发语言·c++
键盘会跳舞13 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出