module - 如何在 Rust cargo 项目中使用另一个模块中的一个模块?

标签 module rust

有很多 Rust documentation关于使用模块,但我还没有找到具有多个模块的 Cargo 二进制文件的示例,其中一个模块使用另一个模块。我的示例在 src 文件夹中包含三个文件。模块 a 和 b 处于同一级别。一个不是另一个的子模块。

主要.rs:

mod a;

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

a.rs:

pub fn a() {
    println!("A");
    b::b();
}

和 b.rs:

pub fn b() {
    println!("B");
}

我已经在 a.rs 中尝试了 use bmod b 的变体,但我无法编译此代码。例如,如果我尝试使用 use b,我会收到以下错误:

 --> src/a.rs:1:5
  |
1 | use b;
  |     ^ no `b` in the root. Did you mean to use `a`?

让 Rust 识别出我想在 cargo 应用程序中使用模块 a 中的模块 b 的正确方法是什么?

最佳答案

您必须在某处包含 b.rs,通常使用 mod b;。如果 ba 的 child (而不是 a 的兄弟),有两种方法可以做到这一点:

  • 推荐:将a.rs重命名为a/mod.rs,将b.rs重命名为a/b.rs。然后你可以在a/mod.rsmod b;
  • 相反,您可以在 a.rs 中直接使用 #[path = "b.rs"] mod b; 而无需重命名源。

如果 ba 的 sibling (而不是 a 的 child ),你可以 mod b;main.rs 中,然后在 a.rs 中使用 use crate::b;

关于module - 如何在 Rust cargo 项目中使用另一个模块中的一个模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809744/

相关文章:

function - Rust 仅在拆分为多个语句时才编译方法链

rust - Rust 教科书的猜谜游戏扩展显示出奇怪的行为

rust - 添加生命周期参数时借用中断

java - Gradle 构建错误 : Failed to appy plugin[class 'org. gradle.api.plugins.JavaPlugin

types - 具有参数类型的第一类模块(类型构造函数 F.f 将逃脱其范围)

python - 使用 Python 实现负载均衡

rust - 创建一个具有可交换功能的结构

proxy - 在防火墙后面时,如何在 Windows 上使用 rustup 安装 Rust?

swift - 无法将模块导入 xcode

templates - 自定义 Prestashop 管理模块