如何从 `src` 目录之外的目录导入模块?
How to import a module from a directory outside of the `src` directory?
我在学习如何访问模块时卡住了。我正在尝试将 src
以外的文件夹插入 src
。它不工作,它给了我一个错误。这是我的项目树。
$ Project1
.
|-- src
| |-- main.rs
| |--FolderinSrcFolder
| |--folderinsrcmodule.rs
|
|--anothersrc
| |--mod.rs
|
|-- rootmodule.rs
|-- Cargo.toml
|-- Cargo.lock
如何访问 anothersrc/mod.rs
src/main.rs
?如何从 src/main.rs
访问 rootmodule.rs
?
我已经阅读了 Rust 文档。
惯用的解决方案
不要。将所有源代码放入 src
目录。您还可以使用自己的 src
目录创建另一个 crate。不要和这些成语和约定作对,根本不值得。
另请参阅:
- Rust package with both a library and a binary?
文字解
这直接回答了你的问题,但我强烈建议你不要实际使用这个!
布局
.
├── Cargo.toml
├── bad_location.rs
└── src
└── main.rs
src/main.rs
#[path = "../bad_location.rs"]
mod bad_location;
fn main() {
println!("Was this a bad idea? {}", bad_location::dont_do_this());
}
badlocation.rs
pub fn dont_do_this() -> bool {
true
}
关键是 #[path]
注释。
另请参阅:
- How do I import from a sibling module?
我在学习如何访问模块时卡住了。我正在尝试将 src
以外的文件夹插入 src
。它不工作,它给了我一个错误。这是我的项目树。
$ Project1
.
|-- src
| |-- main.rs
| |--FolderinSrcFolder
| |--folderinsrcmodule.rs
|
|--anothersrc
| |--mod.rs
|
|-- rootmodule.rs
|-- Cargo.toml
|-- Cargo.lock
如何访问 anothersrc/mod.rs
src/main.rs
?如何从 src/main.rs
访问 rootmodule.rs
?
我已经阅读了 Rust 文档。
惯用的解决方案
不要。将所有源代码放入 src
目录。您还可以使用自己的 src
目录创建另一个 crate。不要和这些成语和约定作对,根本不值得。
另请参阅:
- Rust package with both a library and a binary?
文字解
这直接回答了你的问题,但我强烈建议你不要实际使用这个!
布局
.
├── Cargo.toml
├── bad_location.rs
└── src
└── main.rs
src/main.rs
#[path = "../bad_location.rs"]
mod bad_location;
fn main() {
println!("Was this a bad idea? {}", bad_location::dont_do_this());
}
badlocation.rs
pub fn dont_do_this() -> bool {
true
}
关键是 #[path]
注释。
另请参阅:
- How do I import from a sibling module?