You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust的examples目录中添加公共模块并导入使用?

Rust Examples目录下共享公共模块的实现方法

方法一:子目录式公共模块(推荐)

这种方式能统一管理公共代码,避免重复声明,适合多示例共享模块的场景。

1. 调整文件结构

把公共模块放到examples下的common子目录,并新增mod.rs作为模块入口:

examples
|- example1_main.rs
|- example2_main.rs
|- common
   |- mod.rs
   |- example_common1.rs
   |- example_common2.rs

2. 配置模块入口

在common/mod.rs中声明对外暴露的公共模块:

pub mod example_common1;
pub mod example_common2;

用pub修饰确保外部示例文件可以访问这些模块。

3. 在示例文件中导入使用

在example1_main.rs或example2_main.rs里,通过crate路径导入模块:

// 导入整个模块
use crate::common::example_common1;
// 直接导入模块内的具体项
use crate::common::example_common2::some_utility_func;

fn main() {
    example_common1::do_task();
    some_utility_func();
}

方法二:直接引用同目录模块(简单场景)

如果公共模块数量少、场景简单,可以直接在每个示例文件中声明并引用:
在example1_main.rs开头添加:

// 声明同目录下的公共模块
mod example_common1;
mod example_common2;

// 导入模块内容
use example_common1::*;
use example_common2::*;

fn main() {
    common_func_1();
    common_func_2();
}

注意:这种方式需要在每个示例文件中重复声明mod,维护成本略高。

内容的提问来源于stack exchange,提问作者azyx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 22:12:37