Idiomatic module hierarchy organization?

Hi peoples, :slight_smile:

My code is slowly growing and I start to separate things. Here is my package structure:


As you can see, I have a ecs module definition:

mod blah;
use blah::my_func;

With that, I started by putting mod ecs; in

mod ecs;

fn main() {

But in order to build my tests, I realized I can't call use crate::ecs::my_func; inside them, but use the absolute crate path use engine::ecs::my_func;.

// tests/
use engine::ecs::my_func;

This makes senses as tests are separated binaries so I suspect its legit.

To do so, I needed to have with pub mod ecs;:

pub mod ecs;

Doing so, I realize I'm in a kinda mixed crate definition cause by having both and :confused:

For example, to call from I must call super:::

// use // doesn't work

But here is my problem now: I want to use functions from inside ecs/ without relying on the absolute path: I don't want my code inside ecs/ to have use engine::.

// ecs/
// use; // I don't want that.
use ?

Regarding this, I think I am wrong in the way I organize my work. I think my problem is related to mix in crate definition, but depicts looking in various places, I can't find nice solution.

The book explains how module system works, but not how you should organize your code base.

So here I am, asking to you peoples: How would you organize this repo? Of course, the number of submodules would grow in time:

    ecs/ // calling mod1 and
    mod1/ // calling

Thanks in advance.

Every file should have exactly one mod declaration, and all other uses should be use declarations. It belongs in lib, and to access from, you should use it as if it was a separate crate.

use whatever_you_named_your_package_in_cargo_toml::ecs::*;

Tests are also separate crates, and should use the same path. Tests cannot access anything defined in

1 Like

Thanks @alice!

I just tried and it worked perfectly:

  • All mod foo in
  • Full path in and tests.
  • use crate:: everywhere.

Last question: This also mean I need to put everything in in pub in order to test them? Is there special rules to avoid marking module public but allow tests to work?

Thanks again for your precious help! :slight_smile:

Tests in the tests/ folder can only access public items. You can use a test module inside the library to test private things.

// your
mod tests {
    // test private things in here
1 Like

Thanks! Both could coexists:

  • Private tests for library internals.
  • Public tests for library API.

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