当两个子模块都在同一个主模块中时,从另一个子模块访问子模块

Access submodule from another submodule when both submodules are in the same main module

我正在使用 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 `???`

我错过了什么?谢谢。

问题是 use 路径是 绝对路径,而不是相对路径 。当你说 use A; 时,你实际上说的是 "use the symbol A in the root module of this crate",也就是 lib.rs.

你需要使用的是use super::A;,或者完整路径:use foo::A;.

我写了一篇关于 Rust's module system and how paths work that might help clear this up if the Rust Book chapter on Crates and Modules 没有的文章。