【问题标题】:Rust - Include rust module in another directoryRust - 在另一个目录中包含 rust 模块
【发布时间】:2020-08-31 04:24:54
【问题描述】:

这是我的目录结构

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 中的东西吗?

【问题讨论】:

标签: rust


【解决方案1】:

您可以使用一大堆 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

你可以阅读更多关于here

另外,最好为您的 crate 创建一个 prelude mod 并在其中包含您 crate 的所有主要项目,这样您就可以通过传递 use crate::prelude::* 来包含它们。 你可以阅读更多关于preludein offical rust docshere的信息。

【讨论】:

    【解决方案2】:

    在我的src/pages/home_page.rs 中,我可以使用我的标题,例如:use crate::components::header::Header;

    【讨论】:

      猜你喜欢
      • 2014-12-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      相关资源
      最近更新 更多