如何在 Rust 货物项目中使用另一个模块中的一个模块? [英] How to use one module from another module in a Rust cargo project?

查看:27
本文介绍了如何在 Rust 货物项目中使用另一个模块中的一个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. My example has three files inside the src folder. Modules a and b are at the same level. One is not a submodule of another.

main.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,则会出现以下错误:

I've tried variations of use b and mod b inside a.rs, but I cannot get this code to compile. If I try to use use b, for example, I get the following error:

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

让 Rust 认识到我想在货物应用程序中使用模块 a 中的模块 b 的正确方法是什么?

What's the right way to have Rust recognize that I want to use module b from module a inside a cargo app?

推荐答案

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

You'll have to include b.rs somewhere, typically with mod b;. If b is a child of a (instead of being a sibling of a), there are two ways to do this:

  • 推荐:将a.rs重命名为a/mod.rs,将b.rs重命名为a/b.rs.然后你可以在a/mod.rsmod b;.
  • 相反,您可以在 a.rs 中仅 #[path = "b.rs"] mod b; 而无需重命名源.
  • Recommended: rename a.rs into a/mod.rs and b.rs into a/b.rs. Then you can mod b; in a/mod.rs.
  • Instead, you can just #[path = "b.rs"] mod b; in a.rs without renaming sources.

如果 ba 的兄弟(而不是 a 的孩子),你可以只 mod b;main.rs 中,然后 use crate::b;a.rs 中.

If b is intended to be a sibling of a (instead of being a child of a), you can just mod b; in main.rs and then use crate::b; in a.rs.

这篇关于如何在 Rust 货物项目中使用另一个模块中的一个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆