如何在Rust货运项目中使用另一个模块中的一个模块? [英] How to use one module from another module in a Rust cargo project?
问题描述
关于使用模块的很多Rust 文档,但是我尚未找到具有多个模块,一个模块使用另一个模块的Cargo二进制示例.我的示例在src文件夹中有三个文件.模块a和b处于同一级别.一个不是另一个的子模块.
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 b
和mod b
的变体,但是无法编译此代码.例如,如果尝试使用use b
,则会出现以下错误:
--> src/a.rs:1:5
|
1 | use b;
| ^ no `b` in the root. Did you mean to use `a`?
让Rust识别出我想在货运应用程序中使用模块a中的模块b的正确方法是什么?
您必须在通常包含mod b;
的位置添加b.rs
.如果b
是a
的子代(而不是a
的同级),则有两种方法可以做到这一点:
- 推荐:将
a.rs
重命名为a/mod.rs
,将b.rs
重命名为a/b.rs
.然后您可以在a/mod.rs
中的mod b;
. - 相反,您可以在
a.rs
中仅#[path = "b.rs"] mod b;
而不重命名源.
如果打算将b
用作a
的同级兄弟(而不是a
的子级),则可以在main.rs
中仅使用mod b;
,然后在a.rs
中使用use crate::b;
. /p>
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();
}
and 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. 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`?
What's the right way to have Rust recognize that I want to use module b from module a inside a cargo app?
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:
- Recommended: rename
a.rs
intoa/mod.rs
andb.rs
intoa/b.rs
. Then you canmod b;
ina/mod.rs
. - Instead, you can just
#[path = "b.rs"] mod b;
ina.rs
without renaming sources.
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屋!