Sebastian Berglönn
Sebastian Berglönn

Reputation: 4278

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.

My components/mod.rs looks like this: pub mod header; which works fine because inside lib.rs - I can use it like:

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

However, I don't know how to access it in pages/homepage.rs. How can get access to that struct? Is it something in Cargo.toml?

Upvotes: 7

Views: 2238

Answers (2)

Dmitry
Dmitry

Reputation: 1637

You can use a whole bunch of Rust keywords to navigate between the modules of your 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:

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::*. You can read more about prelude in offical rust docs and here.

Upvotes: 7

Sebastian Berglönn
Sebastian Berglönn

Reputation: 4278

Inside my src/pages/home_page.rs I can use my header like: use crate::components::header::Header;

Upvotes: 1

Related Questions