Search code examples
rustrust-cargo

Rust module weird behavior with multiple use from different file


I thought I understood Rust modules, but I am completely lost with mod inconsistencies, at least with my own level of understanding.

I have the following folder structure in my project:

project
|
 - src
   |- main.rs
   |- mod.rs
   |- common
     |- error.rs
     |- global.rs
     |- ids.rs
     |- mod.rs
   - user_info
     |- user.rs
     |- admin.rs
     |- mod.rs
   - data_source
     |- data_src.rs
     |- data_bridge.rs
     |- data_copies.rs
     |- mod.rs

As you may see all folders have a mod.rs file, which basically contains pub mod declaration to all the sub-folders or folder-level files in it. Thought that would make importing cleaner.

data_src.rs is importing modules using

use super::*;
use super::super::common::*

data_src.rs is specifically has dependencies on

data_source/data_bridge.rs
common/error.rs
common/global.rs

data_copies.rs is importing modules using

use super::*;
use super::super::common::*

And data_copies.rs has dependencies on

data_source/data_src.rs
data_source/data_bridge.rs
common/error.rs
common/global.rs
common/ids.rs

While compiling using cargo build command I am seeing no errors from data_src.rs, but same is not true for data_copies.rs, where I keep seeing the same error:

use of undeclared crate or module "..."

across all the imported functions from all the files.

This is very unreasonable for me, because I am using the same use command to import mods in data_src.rs file where it does not throw any error, but only in data_copies.rs.

I checked online, but I cannot find any theaory or explaination remotely helping me understand the problem. Can someone tell me what is going on.


Solution

  • Rust has two kinds of crates, binaries and libraries.

    A binary is a crate that has an entry point and runs directly in the machine. And library is a crate that doesn't has an entry point, is a crate that can be used in other crates.

    When you're writing crates cargo starts reading it from the main file, which is src/main.rs for binaries, and src/lib.rs for libraries.

    Although the modules are declared through rs files which same name as the module, or through a folder with a mod.rs file. The top level modules need be declared in the main file, and this is your problem.

    Your problem is you're declaring your top level in src/mod.rs and cargo don't know how to import them, all you need is move your top level declaration to src/main.rs instead of src/mod.rs.