【问题标题】:How to correctly include files in rust?如何正确地将文件包含在 rust 中?
【发布时间】:2022-01-11 05:51:54
【问题描述】:

我刚刚开始学习 rust 并且在包含文件时遇到了麻烦。

所以我的问题是,当我想在b.rs 中使用来自a.rsstruct 时,我让它工作的唯一方法是通过绝对路径。所以use 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

【问题讨论】:

标签: rust module include


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2017-06-04
    • 2019-12-07
    • 2014-01-12
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多