[英]Rust - Include rust module in another directory
This is my directory structure这是我的目录结构
src/
├── lib.rs
├── pages/
│ ├── mod.rs
│ ├── home_page.rs
└── components/
├── mod.rs
└── header.rs
Inside my pages/home_page.rs
I try to access my pub struct Header
which is inside components/header.rs
.在我的
pages/home_page.rs
我尝试访问我的pub struct Header
,它位于components/header.rs
。
My components/mod.rs
looks like this: pub mod header;
我的
components/mod.rs
看起来像这样: pub mod header;
which works fine because inside lib.rs
- I can use it like:这工作正常,因为在
lib.rs
- 我可以像这样使用它:
mod components;
use components::header::Header;
However, I don't know how to access it in pages/homepage.rs
.但是,我不知道如何在
pages/homepage.rs
访问它。 How can get access to that struct?如何访问该结构? Is it something in Cargo.toml?
它是 Cargo.toml 中的东西吗?
You can use a whole bunch of Rust keywords to navigate between the modules of your crate:你可以使用一大堆 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
And to include submodules of current mod:并包含当前 mod 的子模块:
self::submodule1::MyStruct
// `self` is like current module
You can read more about that here你可以在这里阅读更多相关信息
Also it is good idea to make a prelude
mod of your crate and include all main items of your crate there, so then you can include them just by passing use crate::prelude::*
.此外,最好为您的 crate 制作一个
prelude
mod 并将您的 crate 的所有主要项目包含在其中,这样您就可以通过传递use crate::prelude::*
来包含它们。 You can read more about prelude
in offical rust docs and here .您可以在官方 Rust 文档和此处阅读有关
prelude
更多信息。
在我的src/pages/home_page.rs
我可以使用我的标题,例如: use crate::components::header::Header;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.