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 子模块;

相关推荐
irving同学4623811 小时前
从零搭建生产级 RAG:Embedding、Chunking、Hybrid Search 与 Reranker
前端·后端
她的男孩12 小时前
从零搭一个企业后台,为什么我把能力拆成 Starter 和 Plugin
java·后端·架构
胡志辉12 小时前
本地 AI 编码助手从 0 配起来:先选模型,再接 Ollama、VS Code、Claude Code 和 Codex
前端·后端
RainCity12 小时前
Java Swing 自定义组件库分享(七)
java·笔记·后端
啷里格啷12 小时前
第二章 Fast-DDS 整体架构与分层框架
后端·架构
DolphinDB12 小时前
漫长人工,耗费存储?用 BackupRestore 模块一站式解决跨环境数据同步难题
运维·后端·架构
钟智强12 小时前
硬核自研|HunTianDB 混天DB:Rust原生工业级时序安全数据库全技术拆解
后端
_遥远的救世主_12 小时前
从一次结果集密集型查询 OOM 看 Java 服务的稳定性架构治理
java·后端
代码丰12 小时前
基于数据库字段实现可续期分布式锁:从任务抢占到心跳续约
后端
hhb_61812 小时前
Swift核心技术难点与实战案例解析
开发语言·ios·swift