在同一主模块中,如何从一个子模块访问另一个子模块?

14

我正在使用 rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14),并且我有以下设置:

my_app/
|
|- my_lib/
|   |
|   |- foo
|   |   |- mod.rs
|   |   |- a.rs
|   |   |- b.rs
|   |
|   |- lib.rs
|   |- Cargo.toml
|
|- src/
|   |- main.rs
|
|- Cargo.toml

src/main.rs:

extern crate my_lib;

fn main() {
  my_lib::some_function();
}

my_lib/lib.rs:

pub mod foo;

fn some_function() {
  foo::do_something();
}

my_lib/foo/mod.rs:

pub mod a;
pub mod b;

pub fn do_something() {
  b::world();
}

my_lib/foo/a.rs:

pub fn hello() {
  println!("Hello world");
}

my_lib/foo/b.rs:

use a;
pub fn world() {
  a::hello();
}

Cargo.toml:

[dependencies.my_lib]
path = "my_lib"

编译时,我在B.rs中的use语句处遇到以下错误:

unresolved import `A`. There is no `A` in `???`

我错过了什么吗?谢谢。

1个回答

15
问题在于使用路径为绝对路径,而非相对路径。当你写 use A; 时,实际上是在说“在这个 crate 的根模块中使用符号 A”,也就是指的是 lib.rs
你需要使用的是 use super::A; 或者完整路径: use foo::A;
我写了一篇关于 Rust 模块系统及其路径工作原理 的文章,如果 Rust Book 中的 Crates and Modules 章节 没有解决你的问题,或许可以帮到你。

是的,抱歉,B::world() 确实被包含在另一个函数中。我正在使用 cargo 编译项目。那可能是 cargo 的一个错误? - morcmarc
如果需要使用Cargo进行复现,请发布您的Cargo.toml文件。目前来看,按照给定的示例编译没有问题。 - DK.
它起作用了。感谢您澄清。然而,使用 super::module_name 是否符合习惯用法?感觉有点别扭。 - morcmarc

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