如果您有这样的目录 struct :
src/main.rs
src/module1/blah.rs
src/module1/blah2.rs
src/utils/logging.rs
如何使用其他文件中的函数?
从Rust教程中,听起来我应该能够做到:
main.rs
mod utils { pub mod logging; }
mod module1 { pub mod blah; }
fn main() {
utils::logging::trace("Logging works");
module1::blah::doit();
}
logging.rs
pub fn trace(msg: &str) {
println!(": {}\n", msg);
}
blah.rs
mod blah2;
pub fn doit() {
blah2::doit();
}
blah2.rs
mod utils { pub mod logging; }
pub fn doit() {
utils::logging::trace("Blah2 invoked");
}
但是,这会产生一个错误:
error[E0583]: file not found for module `logging`
--> src/main.rs:1:21
|
1 | mod utils { pub mod logging; }
| ^^^^^^^
|
= help: name the file either logging.rs or logging/mod.rs inside the directory "src/utils"
看来,沿着这条路径导入(即从main
到module1/blah.rs
)是可行的,导入对等点(即从blah
到blah2
)是可行的,但从父范围导入不可行.
如果我使用魔法#[path]
指令,我可以做到:
blah2.rs
#[path="../utils/logging.rs"]
mod logging;
pub fn doit() {
logging::trace("Blah2 invoked");
}
我真的需要手动使用相对文件路径从父作用域级别导入内容吗?有没有更好的方法在铁 rust 中实现这一点?
在Python中,本地范围使用from .blah import x
,但如果想要访问绝对路径,可以使用from project.namespace.blah import x
.