rust - 如何在 Rust 中正确包含文件?

标签 rust module include

我刚刚开始学习 rust,并且在包含文件时遇到困难。

所以我的问题是,当我想在 b.rs 中使用 a.rs 中的 struct 时,这是我获得它的唯一方法工作是通过绝对路径。所以使用 crate::stuff::a::StructA;。根据我所读到的内容,我应该能够在这里使用 mod 因为它位于同一个模块中。

为了回答我的问题,对于具有 c/c++ 和 python 背景的人,我应该如何正确包含内容? (因为这种绝对路径确实感觉不方便。)


目录结构:

src
├── stuff
│   ├── a.rs
│   ├── b.rs
│   └── c.rs
├── stuff.rs
└── main.rs

b.rs:

use crate::stuff::a::StructA;

/* doesn't work
mod stuff;
use stuff::a::StructA;
*/
/* doesn't work
mod a;
use a::StructA;
*/

// Works but why should I define the path. It's in the same dir/mod.
#[path = "a.rs"]
mod a;
use a::StructA;

stuff.rs:

pub mod a;
pub mod b;
pub mod c;

main.rs:

use crate::stuff::a::StructA;
use crate::stuff::b::StructB;
use crate::stuff::c::StructC;

fn main() {
    let a = StructA::new();
    let b = StructB::new(a);
    let c = StructC::new(a, b);
}

b.rsc.rs 使用 a.rs 的部分内容。 main.rs 使用 a.rsb.rsc.rs

编辑: 我还了解到不建议使用 mod.rs

最佳答案

mod 关键字仅用于定义模块,因为您在 stuff.rs 中执行了该操作,所以其他任何地方都不需要它。您想要做的而不是使用绝对路径是use super::a::StructA,其中 super 会将您从使用它的模块提升一级。

关于rust - 如何在 Rust 中正确包含文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70238413/

相关文章:

Typescript 接口(interface)、函数和命名空间都具有相同的名称。哪个正在导出?

c++ - 包括在 C++ 中

c++ - Qt 包含文件

rust - 在可变选项内的值上调用方法

rust - 如何使用 'on_send'镍 react 的方法?

generics - 如何在rust宏中扩展多个特征范围?

java - 导入什么以使用@SuppressFBWarnings?

rust - 为什么在 nightly Rust 1.29 中工作的生成器在 nightly 1.34.0 中出错?

javascript - 鉴于 ES2015、依赖注入(inject)和库抽象,我理想的模块在 2016 年应该是什么样子?

python - 导入 __module__ python : why the underscores?