Rust - 在另一个目录中引用Rust模块

6

这是我的目录结构

src/
├── lib.rs
├── pages/
│   ├── mod.rs
│   ├── home_page.rs
└── components/
    ├── mod.rs
    └── header.rs

在我的pages/home_page.rs文件中,我试图访问components/header.rs中的pub struct Header

我的components/mod.rs文件如下:pub mod header;这是可以正常工作的,因为在lib.rs中,我可以像这样使用:

mod components;
use components::header::Header;

然而,我不知道如何在pages/homepage.rs中访问它。我如何获取该结构的访问权限?这与Cargo.toml有关吗?


1
如果你在Youtube上关注这个人的讲座...视频1和2展示了如何重构一个项目,将其分解成这样的结构。也许这会对你有所帮助。https://www.youtube.com/playlist?list=PLtbwxVtHxPeIYJtu1g53FgLPGN9WYgG2l - JGFMK
2个回答

6

你可以使用一系列Rust关键词来浏览你的crate中的模块:

super::components::Header
// `super` is like a `parent` of your current mod

crate::components::Header
// `crate` is like a root of you current crate

要包括当前模块的子模块:

self::submodule1::MyStruct
// `self` is like current module

关于路径引用模块树中的项目,可以在 这里 阅读更多内容。

此外,制作你的 crate 的 prelude 模块并在其中包含所有主要的项是一个好主意,那么你就可以通过传递 use crate::prelude::* 来直接包含它们。 你可以在 官方 Rust 文档这里 阅读更多关于 prelude 的内容。


1

在我的 src/pages/home_page.rs 文件中,我可以这样使用我的头部:use crate::components::header::Header;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接