我正在使用
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
# Cargo.toml
[dependencies.my_lib]
path = "my_lib"
// 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();
}
当我尝试编译它时,针对
use
中的 B.rs
语句抛出以下错误:
unresolved import `A`. There is no `A` in `???`
我错过了什么?
问题是
use
路径是绝对的,而不是相对的。当你说 use A;
时,你实际上是在说“在这个板条箱的根模块中使用符号 A
”,即 lib.rs
。
您需要使用的是
use super::A;
,即完整路径:use foo::A;
。
我写了一篇关于 Rust 的模块系统以及路径如何工作的文章,如果 Rust Book 关于板条箱和模块的章节没有帮助解决这个问题。