简体   繁体   English

如何在 Rust 货物项目中使用另一个模块中的一个模块?

[英]How to use one module from another module in a Rust cargo project?

There's a lot of Rust documentation about using modules, but I haven't found an example of a Cargo binary that has multiple modules, with one module using another.有很多关于使用模块的 Rust文档,但我还没有找到具有多个模块的 Cargo 二进制文件的示例,其中一个模块使用另一个模块。 My example has three files inside the src folder.我的示例在 src 文件夹中包含三个文件。 Modules a and b are at the same level.模块 a 和 b 处于同一级别。 One is not a submodule of another.一个不是另一个的子模块。

main.rs:主.rs:

mod a;

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

a.rs:答:

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

and b.rs:和 b.rs:

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

I've tried variations of use b and mod b inside a.rs, but I cannot get this code to compile.我在 a.rs 中尝试了use bmod b的变体,但我无法编译此代码。 If I try to use use b , for example, I get the following error:例如,如果我尝试使用use b ,我会收到以下错误:

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

What's the right way to have Rust recognize that I want to use module b from module a inside a cargo app?让 Rust 认识到我想在货物应用程序中使用模块 a 中的模块 b 的正确方法是什么?

You'll have to include b.rs somewhere, typically with mod b;您必须在某处包含b.rs ,通常使用mod b; . . If b is a child of a (instead of being a sibling of a ), there are two ways to do this:如果b是一个孩子a (而不是被的兄弟a ),有两种方法可以做到这一点:

  • Recommended : rename a.rs into a/mod.rs and b.rs into a/b.rs .推荐:重命名a.rsa/mod.rsb.rsa/b.rs Then you can mod b;然后你可以修改mod b; in a/mod.rs .a/mod.rs
  • Instead, you can just #[path = "b.rs"] mod b;相反,你可以#[path = "b.rs"] mod b; in a.rs without renaming sources.a.rs无需重命名源。

If b is intended to be a sibling of a (instead of being a child of a ), you can just mod b;如果b旨在成为的兄弟a (而不是被一个孩子a ),你可以mod b; in main.rs and then use crate::b;main.rs ,然后use crate::b; in a.rs .a.rs

The method from the accepted answer doesn't work for me in Rust 1.33.接受的答案中的方法在 Rust 1.33 中对我不起作用。 Instead, I use the sibling module like this:相反,我像这样使用兄弟模块:

use crate::b;

In the latest Rust 1.63, we can use super keyword to refer siblings在最新的 Rust 1.63 中,我们可以使用super关键字来引用兄弟姐妹

// main.rs
mod a;
mod b;

fn main() {
}

// a.rs
pub fn a() {
    println!("A");
    super::b::b();
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM