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

相关推荐
风逸hhh21 分钟前
python打卡day25@浙大疏锦行
开发语言·python
刚入门的大一新生25 分钟前
C++初阶-string类的模拟实现与改进
开发语言·c++
chxii2 小时前
5java集合框架
java·开发语言
老衲有点帅2 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈2 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
IsPrisoner2 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
Python私教2 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust
chicpopoo3 小时前
Python打卡DAY25
开发语言·python
crazyme_63 小时前
深入掌握 Python 切片操作:解锁数据处理的高效密码
开发语言·python