我刚刚开始学习 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.rs
和 c.rs
使用 a.rs
的部分内容。 main.rs
使用 a.rs
、b.rs
和 c.rs
。
编辑:
我还了解到不建议使用 mod.rs
。
最佳答案
mod
关键字仅用于定义模块,因为您在 stuff.rs
中执行了该操作,所以其他任何地方都不需要它。您想要做的而不是使用绝对路径是use super::a::StructA
,其中 super 会将您从使用它的模块提升一级。
关于rust - 如何在 Rust 中正确包含文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70238413/