• Rust的模块化


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

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

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

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

    怎么理解这个规则,我来举一个例子:
    假设我们目录结构如下:

    src/
      components/
        mod.rs
        table_component.rs
      models/
        mod.rs
        table_row.rs
      main.rs
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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

    main.rs -> table_component.rs -> table_row.rs
    
    • 1

    现在来看看模块之间的引用代码。
    main.rs对table_component.rs的依赖,对应的代码为

    use components::table_component::TableComponent;
    
    • 1

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

    use crate::models::table_row::TableRow;
    
    • 1

    上面的依赖代码都没毛病。在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)过来的同学。

     --> src/main.rs:4:5
    use components::table_component::TableComponent;
         ^^^^^^^^^^ use of undeclared crate or module `components`
    
    • 1
    • 2
    • 3

    上面的错误里中有“undclared crate or module",这里其实就是在提醒我们这个components模块没有被声明。
    很简单,就是在main.rs的头部加上下面的代码。

    mod components;
    
    • 1

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

     --> src/components/table_component.rs:1:12
    
     use crate::models::table_row::TableRow;
                ^^^^^^ could not find `models` in the crate root
    
    • 1
    • 2
    • 3
    • 4

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

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

    mod components;
    mod models;
    
    • 1
    • 2

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

  • 相关阅读:
    马来酰亚胺/碳碳双键表面/硫硅烷基团/金属硫蛋白修饰二氧化硅微球的性能与制备
    笔试,猴子吃香蕉,多线程写法
    php对接飞书机器人
    Spring 学习(二)AOP
    六、程序员指南:数据平面开发套件
    Redis缓存序列化配置
    Rocketmq的集群搭建
    小咖啡馆也能撬动大生意
    LAMP及论坛搭建
    基于pytorch实现模型剪枝
  • 原文地址:https://blog.csdn.net/firefox1/article/details/132635795