如何从src目录之外的目录导入模块? [英] How to import a module from a directory outside of the `src` directory?

查看:96
本文介绍了如何从src目录之外的目录导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习如何访问模块时,我陷入了困境.我试图将src以外的文件夹插入src.它不起作用,给我一个错误.这是我的项目树.

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

如何访问anothersrc/mod.rs src/main.rs?如何从src/main.rs访问rootmodule.rs?

How can I access anothersrc/mod.rs src/main.rs? How can I access rootmodule.rs from src/main.rs?

我已经阅读了Rust文档.

I already read the Rust documentation.

推荐答案

不要.将所有源代码放入src目录.不要与这些习语和惯例作斗争,这根本不值得.

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!

布局

.
├── 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 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?

这篇关于如何从src目录之外的目录导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆