问题
I'm stuck when learning how to access a module. I'm trying to insert a folder other than src
into src
. It's not working and it gives me an error. Here this is my project tree.
$ Project1
.
|-- src
| |-- main.rs
| |--FolderinSrcFolder
| |--folderinsrcmodule.rs
|
|--anothersrc
| |--mod.rs
|
|-- rootmodule.rs
|-- Cargo.toml
|-- Cargo.lock
How can I access anothersrc/mod.rs
src/main.rs
? How can I access rootmodule.rs
from src/main.rs
?
I already read the Rust documentation.
回答1:
Don't. Put all of your source code into the src
directory. Don't fight these idioms and conventions, it's simply not worth it.
Here's a literal answer, but don't actually use this!
Layout
.
├── 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
}
The key is the #[path]
annotation.
See also:
- How can I use a module from outside the src folder in a binary project, such as for integration tests or benchmarks?
- How do I tell Cargo to run files from a directory other than "src"?
- How do I import from a sibling module?
来源:https://stackoverflow.com/questions/58715214/how-to-import-a-module-from-a-directory-outside-of-the-src-directory