如何使用 Cargo/Rust 在模块中包含来自同一目录的文件? [英] How to include files from same directory in a module using Cargo/Rust?

查看:24
本文介绍了如何使用 Cargo/Rust 在模块中包含来自同一目录的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Cargo project consisting of three files in the same directory: main.rs, mod1.rs and mod2.rs.

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

I want to import functions from mod2.rs to mod1.rs the same way I would import functions from mod1.rs to main.rs.
I've read about the file structure required but I don't get it - naming all the imported files mod will lead to minor confusion in the editor and also this just complicates the project hierarchy.

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

Is there a way to import/include files independently of directory structure as I would in Python or C++?

main.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
 --> srcmod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
  |
note: maybe move this module `src` to its own directory via `src/mod.rs`
 --> srcmod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^
note: ... or maybe `use` the module `mod2` instead of possibly redeclaring it
 --> srcmod1.rs:1:5
  |
1 | mod mod2;
  |     ^^^^

我不能使用它,因为它在任何地方都不作为模块存在,而且我不想修改目录结构.

I can't use it as it doesn't exist as a module anywhere, and I don't want to modify the directory structure.

推荐答案

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

All of your top level module declarations should go in main.rs, like so:

mod mod1;
mod mod2;

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

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

use crate::mod2;

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

我建议阅读 新版 Rust 书中关于模块的章节 如果您还没有看过的话——它们可能会让刚接触该语言的人有点困惑.

I'd recommend reading the chapter on modules in the new version of the Rust book if you haven't already - they can be a little confusing for people who are new to the language.

这篇关于如何使用 Cargo/Rust 在模块中包含来自同一目录的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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