solve.rs
中访问parser.rs
和another.rs
模块。如何包含这些模块并使用"use
"语句? 如果不可能,应该如何编写代码结构?下面是应用程序文件夹的树形结构:
app/src
--- main.rs
--- another.rs
--- mod.rs
--- parser/
-------- parser.rs
-------- mod.rs
--- solver/
-------- solve.rs
-------- mod.rs
你的第一个选择是绝对路径:
use crate::parser::Whatever;
use crate::solver::Another;
crate
是一个关键字,代表着 crate 根。
你也可以使用相对路径进行高级应用。这两种解决方案在相关的 Rust 文档 中有很好地讨论。
另外,不要忘记将模块设为公共的。它们默认是私有的,不能从父模块或兄弟模块中访问。
parser/parser.rs
和 another.rs
,您可以使用绝对路径(在此我还使用了 嵌套路径,这不是必需的,但可以使模块结构更清晰):use crate::{
parser::parser,
another,
};
您还可以使用相对路径与super
一起使用,该路径指向父模块。有关更多信息,请参见@Ishmaeel的答案。
关于你的代码结构,看起来有点奇怪为什么要有mod.rs
(不是错误,但只是有点奇怪,特别是0
;如果你喜欢可以完全留下1
和2
,但0
可能会让你感到困惑):
app/src
main.rs
another.rs
mod.rs // 0
parser/
parser.rs
mod.rs // 1
solver/
solve.rs
mod.rs // 2
Regarding 1
and 2
:
mod.rs
was used in the 2015 edition for being able to create nested modules, but is no longer needed in the 2018 edition (assuming that you are using the currently newest and default for cargo 2018 edition, see What are editions?):
A
foo.rs
andfoo/
subdirectory may coexist;mod.rs
is no longer needed when placing submodules in a subdirectory.
Regarding 0
:
The module you are defining via this is actually named mod
(not src
as you may have expected, though I'm not sure at all what you expected here), I'm unsure if you meant to do that. However if you did, there is still a way to access it via r#
- raw identifiers, available since Rust 1.30:
use crate::r#mod;
If you don't want to write r#mod
all over the place, you can use as
like this:
use crate::r#mod as new_name;
Then you can refer to the module via new_name
.