import - 如何使用 Cargo/Rust 在模块中包含同一目录中的文件?

标签 import module rust rust-cargo

我有一个 Cargo 项目,由同一目录中的三个文件组成:main.rs , mod1.rsmod2.rs .

我想从 mod2.rs 导入函数至 mod1.rs就像我从 mod1.rs 导入函数一样至 main.rs .
我已经阅读了所需的文件结构,但我不明白 - 命名所有导入的文件 mod将导致编辑器中的轻微混淆,而且这只会使项目层次结构复杂化。

有没有办法像在 Python 或 C++ 中一样独立于目录结构导入/包含文件?

主要.rs:

mod mod1; // Works

fn main() {
    println!("Hello, world!");
    mod1::mod1fn();
}

mod1.rs:

mod mod2; // Fails

pub fn mod1fn() {
    println!("1");
    mod2::mod2fn();
}

mod2.rs:

pub fn mod2fn() {
    println!("2");
}

构建结果:

error: cannot declare a new module at this location
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
  |
note: maybe move this module `src` to its own directory via `src/mod.rs`
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
note: ... or maybe `use` the module `mod2` instead of possibly redeclaring it
 --> src\mod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^

我不能use因为它不作为模块存在于任何地方,我不想修改目录结构。

最佳答案

所有顶级模块声明都应该放在 main.rs 中,如下所示:

mod mod1;
mod mod2;

fn main() {
    println!("Hello, world!");
    mod1::mod1fn();
}

然后您可以在 mod1使用 crate::mod2:

use crate::mod2;

pub fn mod1fn() {
    println!("1");
    mod2::mod2fn();
}

我建议阅读 the chapter on modules in the new version of the Rust book如果您还没有 - 对于刚接触该语言的人来说,它们可能会有些困惑。

关于import - 如何使用 Cargo/Rust 在模块中包含同一目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845953/

相关文章:

java - 在 Java 中导入类

haskell - 只导入模块的部分功能有什么影响

rust - 如何使用货箱列出项目的源文件?

pointers - Rust 的 Arc 和 Rc 类型与垃圾收集有何不同?

java - Maven javafx :jlink. 如何指定使用的模块路径?

for-loop - 如何通过索引更改元素的 vec 值?

python - Python __import__ 函数中的 `globals` 和 `locals` 参数有什么用?

node.js - ERR_MODULE_NOT_FOUND

delphi - 如何解决 Delphi 包中隐式导入的单元

perl 模块 Class::HPLOO v0.23 安装问题 #2