【问题标题】:How to include a public module located in a subfolder如何包含位于子文件夹中的公共模块
【发布时间】:2021-10-23 17:02:13
【问题描述】:

我有以下项目,我想将一些模块分成子文件夹。 当前的文件结构很简单:

src/
  ->main.rs
  ->cpu/
      ->cpu.rs

main.rs 只包含:

fn main() {
    println!("Hello, world!");

    let c : cpu::Cpu;
    cpu::thing();
}

并且 cpu/cpu.rs 包含一个结构声明和一个测试函数:

pub struct Cpu {
    memory : [u8; 16],
}


pub fn thing() -> u8 {
2 // whatever, it's a test
}

如何将 cpu.rs 公共函数和结构包含到 main.rs 中? 无论我尝试什么,如果我使用 use crate::cpu::{Cpu, thing};,我都会收到错误 (could not find `cpu` in the crate root),而使用 mod cpu; 似乎只能在同一个目录上工作。

在线搜索解决方案非常令人恼火,因为答案在 2015 年和 2018 年的 rust 版本之间混在一起,过于复杂或在同一个文件夹中完成。

【问题讨论】:

    标签: rust


    【解决方案1】:

    您忘记将 cpu(文件夹)本身设置为 mod,您需要在文件夹结构中包含一个 mod.rs 文件:

    src/
      ->main.rs
      ->cpu/
          ->mod.rs
          ->cpu.rs
    

    并在mod.rs 中公开重新导出内部cpu 模块:

    pub mod cpu;
    

    【讨论】:

    • 谢谢,但不鼓励使用mod.rs 吗? (同样,我在指南和其他问题中发现了关于 mod.rs 的混合反应)。如果是这样,Rust 2018 的做法是什么?
    • @Lightsong 嗯,如果您想保留该文件夹,我认为没有其他选择。否则,只需使用 cpu.rs 文件,您就可以在模块调用中从主取消嵌套 cpu 中调用它。
    • 好的,谢谢! use 在 main.rs 中会是什么样子?我不得不使用mod cpu;use crate::cpu::cpu::{Cpu, thing};,这看起来非常奇怪。
    • 只需在 main 中使用mod cpu;,然后您就可以从那里访问它;板条箱的东西也不错。
    • 如果你不想要重复的cpu,那么不要在你的文件层次结构中复制它:要么去掉cpu文件夹,让cpu.rs在同一个文件夹中main.rs,或者将cpu.rs的内容直接放到cpu/mod.rs中。
    猜你喜欢
    • 2016-10-04
    • 2018-09-01
    • 1970-01-01
    • 2013-01-23
    • 2015-02-12
    • 1970-01-01
    • 2021-05-22
    • 2022-11-15
    • 2014-11-26
    相关资源
    最近更新 更多