How to name nested modules?

I have the following structure:

src/
    lib.rs
    foo/
        mod.rs
        foo.rs

foo.rs contains a function start_foo() The problem is that inside of lib.rs, I have to call/use it like super::foo::foo::start_foo(); instead of just super::foo::start_foo()

How can I get rid of the extra foo ? Note that I still want the files to be in the foo/ folder, and I’d prefer not needing to rename foo.rs to something else

In src/foo/mod.rs, you could do a

pub use self::foo::*

This would export everything in foo/foo.rs into foo/mod.rs

I personally would not use this layout, but I think it solves your problem.

1 Like

Thanks! what layout would you suggest as an alternative?

  1. I’m a Rust beginner myself and am still trying to figure out what style I want.
  2. My current system uses the following rules:

2a. Every file has use super::*
2b. I never use use ::* anywhere else.
2c. Every mod.rs contains a number of pub use self::BLAHBLAH::{ STUFF TO EXPORT} which exports things “one level up”

This isn’t perfect/ideal by any means, but it has the advantage that at any time, I can look at a mod.rs and know “what is everything I am exporting upwards” ?

1 Like

would it be nice if foo/foo.rs were treated as foo/mod.rs? Seems like that magic already sortof happens within a directory…

The problem is that you declared a second module foo inside your module foo.
There are two ways to organize your files:

  1. mod.rs inside module-folder:
    As you have done the main-file of module bar is placed in folder bar and is named mod.rs. Modules without child-modules are placed in files named after their module, e.g. baz.rs. So your example means your library has a module foo placed in foo/mod.rs and foo has a module foo placed in foo/foo.rs.
    However, the problem is that when you use this layout you have to reorganize your folders when you deside that a module should get child-modules.
  2. bar.rs and bar/ on the same level:
    I’m not realy sure but I think this was introduced in 2018 edition.
    You can name your main-module-file like the module itself as well as the folder where the nested modules are placed.
    Advantage of this is that you don’t have to change your folder structure if you add nested modules.
    For example:
src/
  lib.rs
  foo.rs      // module of lib
  foo/        // nested modules of foo placed here
    bar.rs    // module of foo
  baz.rs      //module of lib without child-modules
2 Likes