如何从父文件夹或同级文件夹的模块中访问模块?

4
我正在尝试在solve.rs中访问parser.rsanother.rs模块。如何包含这些模块并使用"use"语句? 如果不可能,应该如何编写代码结构?
下面是应用程序文件夹的树形结构:
app/src
--- main.rs
--- another.rs
--- mod.rs
--- parser/
-------- parser.rs
-------- mod.rs
--- solver/
-------- solve.rs
-------- mod.rs
2个回答

3

你的第一个选择是绝对路径:

use crate::parser::Whatever;
use crate::solver::Another;

crate 是一个关键字,代表着 crate 根。

你也可以使用相对路径进行高级应用。这两种解决方案在相关的 Rust 文档 中有很好地讨论。

另外,不要忘记将模块设为公共的。它们默认是私有的,不能从父模块或兄弟模块中访问。


1
感谢您的帮助。我仍然无法引用对象。然后我尝试了这个: “use project_name::parser::Whatever;” 这个方法可行。 - Nilanjan Goswami

1
要从您的箱中的任何位置访问 parser/parser.rsanother.rs,您可以使用绝对路径(在此我还使用了 嵌套路径,这不是必需的,但可以使模块结构更清晰):
use crate::{
    parser::parser,
    another,
};

您还可以使用相对路径与super一起使用,该路径指向父模块。有关更多信息,请参见@Ishmaeel的答案


关于你的代码结构,看起来有点奇怪为什么要有mod.rs(不是错误,但只是有点奇怪,特别是0;如果你喜欢可以完全留下12,但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 and foo/ 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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接