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

Rust多文件代码拆分:指定引用关系配置方案咨询

Rust 非树形结构的模块配置方案

要实现你需求的模块访问关系,只需把所有模块都声明在lib.rs的顶层,将three和four设为公共模块即可。以下是每个文件的具体配置:

1. lib.rs(根模块)

这里声明所有顶层模块,其中three和four标记为pub,允许其他模块访问:

// 声明公共模块,供所有其他模块访问
pub mod three;
pub mod four;

// 声明 one 和 two 模块
pub mod one;
pub mod two;

2. one.rs

通过crate::前缀直接访问顶层的公共模块three和four:

// 引入所需的公共模块
use crate::{three, four};

// 示例:使用 three 和 four 中的功能
pub fn demo_one() {
    three::print_three();
    four::print_four();
}

3. two.rs

和one.rs逻辑一致,同样通过crate::访问公共模块:

use crate::{three, four};

pub fn demo_two() {
    three::print_three();
    four::print_four();
}

4. three.rs

作为公共模块,对外暴露需要被访问的函数/结构体:

pub fn print_three() {
    println!("来自 three 模块的内容");
}

5. four.rs

同理,暴露公共接口:

pub fn print_four() {
    println!("来自 four 模块的内容");
}

访问逻辑说明

  • lib.rs可以直接调用one::demo_one()、two::demo_two(),也能直接使用three::print_three()、four::print_four()
  • one.rs和two.rs通过crate::three、crate::four访问公共模块内容,无需嵌套在父模块下
  • 所有模块都处于根模块的同一层级,完全避开树形嵌套结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:15:31