DEV Community

Discussion on: Rust Module Essentials

Collapse
 
zinsbill profile image
zinsbill

I’m unable to understand how "mod" works. I've read chapt-7 from the book, read questions posted in various discussions and I’ve read tutorials. I can get mod to do simple, basic stuff, but nothing beyond the primitive examples supplied.

Similar to an example in the book, let’s say a project is divided in 2 directories:

src
└── front_of_restaurant
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
└── back_of_restaurant
├── cooking
│ ├── prepare_appetizers
│ └── cook_main_dishes
│ └── prepare_dessert
│ └── clean_up
└── management
├── order_supplies
├── assign_work
└── balance_accounts

What I feel the documentation does not cover is if, from take_payment, I need to call balance_accounts, located in a very different section of the code.

So I'm several levels down in front_of_restaurant and I want to call down into back_of_restaurant. In the calling code (in take_payment), I've tried the following:

mod back_of_restaurant;
pub mod back_of_restaurant;
mod src::back_of_restaurant;
use back_of_restaurant;
use std::back_of_restaurant;
mod ::back_of_restaurant;
mod crate::back_of_restaurant;
...and several other variations.

[Of course, I could also include the actual call itself, but the compiler never gets that far.]

All variations fail. Most result in:
^ no 'back_of_restaurant' in the root (or worse errors)

No 'back_of_restaurant' in the root? Looks to me like it’s there. I can code "mod back_of_restaurant" in main.rs up at the top (i.e., src dir) level and it works great. From main, starting at the top, I can run balance_accounts with no problem (after qualifying it properly). Why can this not be done from take_payment? I’ve coded "pub" in all legitimate locations, so I don’t think it’s a visibility issue.

I find this quite frustrating because much of the discussion printed in the documentation deals with "absolute paths". But if absolute paths were really in effect, I should be able to move a module to any arbitrary location and it would still find balance_accounts. Currently only main (top level) or "cousin" modules within back_of_restaurant succeed with the mod statement.

Can anyone enlighten me? If this is clearly explained somewhere, feel free to berate me and call me names (but just remember to tell me where the explanation can be found). If it’s not explained somewhere, then how did you figure out how mod works?

Collapse
 
hertz4 profile image
Sam Pagenkopf
// main.rs
mod back_of_restaurant;

// front_of_restaurant
use back_of_restaurant;
Collapse
 
zinsbill profile image
zinsbill

name the file either back_of_restaurant.rs or back_of_restaurant/mod.rs inside the directory "src/front_of_restaurant"