How to use a module from another module?

Directory structure (omitting some directories for brevity):

  • db
      - mod.rs // this contains some public methods
      - connection.rs
  • index
      - mod.rs // the public methods from db needs to be used here
      - logic.rs
  • // Ignoring directories for brevity
  • main.rs // the main method and basic handlers are here

I need to use the db::create_pool() method in the db module from index. How can I achieve this?

To use modules, you have to do two things:

  1. Declare that they exist. It’s not enough to have files, you must also have code that says to use each file.

  2. Refer to module’s path, and optionally make a shorter alias with use

The first is in main.rs:

mod db;
mod index;

and then in each module declare their submodules.
mod behaves same as fn/struct/enum - it creates a new item with that name, in the parent module where you invoke it.

And then crate::db will refer to your db module. use crate::db allows you to refer to just db in the scope of the use.

1 Like

Achieved it without the need for that;
Just added use crate::db; to my index module. There’s no need for re-exporting it!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.