当两个子模块在同一个主模块中时,从另一个子模块访问子模块 [英] 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)
并且我有以下设置:
I'm using rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)
and I've got the following setup:
my_app/
|
|- my_lib/
| |
| |- foo
| | |- mod.rs
| | |- a.rs
| | |- b.rs
| |
| |- lib.rs
| |- Cargo.toml
|
|- src/
| |- main.rs
|
|- Cargo.toml
src/main.rs:
src/main.rs:
extern crate my_lib;
fn main() {
my_lib::some_function();
}
my_lib/lib.rs:
my_lib/lib.rs:
pub mod foo;
fn some_function() {
foo::do_something();
}
my_lib/foo/mod.rs:
my_lib/foo/mod.rs:
pub mod a;
pub mod b;
pub fn do_something() {
b::world();
}
my_lib/foo/a.rs:
my_lib/foo/a.rs:
pub fn hello() {
println!("Hello world");
}
my_lib/foo/b.rs:
my_lib/foo/b.rs:
use a;
pub fn world() {
a::hello();
}
Cargo.toml:
Cargo.toml:
[dependencies.my_lib]
path = "my_lib"
当我尝试编译它时,B.rs
中的 use
语句抛出以下错误:
When I try to compile it I get the following error thrown for the use
statement in B.rs
:
unresolved import `A`. There is no `A` in `???`
我错过了什么?谢谢.
推荐答案
问题在于 use
路径是绝对的,而不是相对的.当您说 use A;
时,您实际上是在说在此 crate 的根模块中使用符号 A
",即 lib.rs代码>.
The problem is that use
paths are absolute, not relative. When you say use A;
what you are actually saying is "use the symbol A
in the root module of this crate", which would be lib.rs
.
你需要使用的是use super::A;
,或者完整路径:use foo::A;
.
What you need to use is use super::A;
, that or the full path: use foo::A;
.
我写了一篇关于 Rust 的模块系统以及路径如何工作 的文章,这可能有助于澄清如果 Rust Book 关于 Crates 和模块的章节 没有
I wrote up a an article on Rust's module system and how paths work that might help clear this up if the Rust Book chapter on Crates and Modules doesn't.
这篇关于当两个子模块在同一个主模块中时,从另一个子模块访问子模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!