gpt4 book ai didi

module - 如何从 `src` 目录之外的目录导入模块?

转载 作者:行者123 更新时间:2023-11-29 08:23:10 25 4
gpt4 key购买 nike

我在学习如何访问模块时卡住了。我正在尝试将 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 目录。您还可以创建另一个 crate,它有自己的 src 目录。不要与这些成语和惯例作斗争,这根本不值得。

另见:

文字解

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

布局

.
├── 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]注解。

另见:

关于module - 如何从 `src` 目录之外的目录导入模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com