[英]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 b
和mod 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
),有两种方法可以做到这一点:
a.rs
into a/mod.rs
and b.rs
into a/b.rs
.推荐:重命名a.rs
到a/mod.rs
和b.rs
到a/b.rs
。 Then you can mod b;
然后你可以修改mod b;
in a/mod.rs
.在a/mod.rs
。#[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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.