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

相关推荐
君顾13 分钟前
酒吧点餐小程序系统开发实战:从架构设计到上线全流程指南
java·开发语言·酒吧
行百里er14 分钟前
BeanPostProcessor:包装 Feign Client
spring boot·后端·监控
花生了什么事o24 分钟前
自定义Spring Boot Starter全流程
java·spring boot·后端
似水এ᭄往昔27 分钟前
【Qt】--常用控件(显示类控件)
开发语言·qt
PHP实战开发录37 分钟前
PHP文件上传成功为什么页面却找不到
开发语言·nginx·php·开发
云上小朱1 小时前
开发测试环境-Kubernetes离线部署指南
后端
遨翔在知识的海洋里1 小时前
nestjs(1)-模块的相互调用
后端
Profile排查笔记1 小时前
指纹浏览器推荐:用一套验收清单筛选 Profile、代理与自动化能力
前端·人工智能·后端·自动化
jsl_jsl_jsl1 小时前
JUC速记
后端
站大爷IP1 小时前
Python的pip依赖把我折腾惨了,原来requirements.txt和poetry能打出火星撞地球
后端