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

查看:31
本文介绍了如何从`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 目录.您还可以使用自己的 src 目录创建另一个 crate.不要与这些习语和惯例作斗争,这根本不值得.

Idiomatic solution

Don't. Put all of your source code into the src directory. You could also create another crate with its own src directory. Don't fight these idioms and conventions, it's simply not worth it.

另见:

这直接回答了您的问题,但我强烈建议您实际上不要使用它

This directly answers your question, but I strongly recommend that you 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]注解.

另见:

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

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