Rust 的 mod(模块) 说明

模块(Module) 是 Rust 中用来分割和组织代码的基本单元。

怎么在Rust中创建模块?

  1. 使用 mod 关键字创建模块

    直接在代码中用mod创建模块

    复制代码
    mod front_of_house {
     pub mod hosting {
         pub fn add_to_waitlist() {}
     }
    }
  2. 使用单独的文件作为模块

    在该文件中直接写上我们需要的代码,如:

    复制代码
    // 文件 src/front_of_house.rs
         fn take_order() {}
         fn serve_order() {}
         fn take_payment() {}
  3. 使用 mod.rs 文件的目录定义模块

    可以在包含mod.rs的文件目录中来定义模块,并且可以在mod.rs文件中声明和加载当前目录下的子模块,如:

    复制代码
    ├── memory_pools
    ├── config.rs
    ├── fair_pool.rs
    ├── logging_pool.rs
    ├── mod.rs
    ├── task_shared.rs
    └── unified_pool.rs

    mod.rs中的内容如下:

    复制代码
    mod config;
    mod fair_pool;
    pub mod logging_pool;
    mod task_shared;
    mod unified_pool;
    
    use datafusion::execution::memory_pool::{
        FairSpillPool, GreedyMemoryPool, MemoryPool, TrackConsumersPool, UnboundedMemoryPool,
    };
    use fair_pool::CometFairMemoryPool;
    use jni::objects::GlobalRef;
    use once_cell::sync::OnceCell;
    use std::num::NonZeroUsize;
    use std::sync::Arc;
    use unified_pool::CometUnifiedMemoryPool;
    
    pub(crate) use config::*;
    pub(crate) use task_shared::*;

    在以上中声明了子模块 config fair_pool(如果 mod.rs 文件中没有写 mod 子模块;,即使子文件存在,其内容也不会被编译) 等,并且通过pub(crate) use config::*重新导出子模块中的内容,方便外部调用;

    通过 use fair_pool::CometFairMemoryPool 使用 fair_pool模块中的CometFairMemoryPool结构体.
    注意在 Rust 中,所有项(函数、方法、结构体、枚举、模块和常量)默认对父模块都是私有的,如果需要让上级模块访问子模块的内容,通常需要配合 pub 使用,例如 pub mod 子模块;

相关推荐
卷福同学2 小时前
不用服务器,不用配环境,我10分钟上线了一个AI Agent
人工智能·后端·算法
码兄科技3 小时前
Java AI智能体开发实战:从零构建智能对话系统指南
java·开发语言·人工智能
花褪残红青杏小4 小时前
Rust图像处理第14节-图片缩放与斜切畸变:齐次坐标 + 共享仿射变换
rust·webassembly·图形学
GetcharZp5 小时前
只需 10 分钟,轻松实现异地组网!Netmaker 保姆级部署教程来了
后端
Drone_xjw5 小时前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
前端兰博5 小时前
03-Spring Boot
后端
前端兰博5 小时前
01-Java开发基础语言
后端
SL-staff5 小时前
智慧园区2000+设备统一管理:JVS-IoT如何降低运维成本40%
java·开发语言·物联网·智慧园区·设备管理·运维优化·jvs-iot
前端兰博5 小时前
02-Servlet、JDBC、Maven、Mybatis
后端
咖啡八杯6 小时前
GoF设计模式——模板方法模式
java·后端·spring·设计模式