How to import a module from a directory outside of the `src` directory?

一个人想着一个人 提交于 2020-02-03 01:43:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!