How to use multiple subdirectories inside "src"?

Let's say that I have the following structure in my project:

Cargo.toml
src
  | main.rs
  | commons.rs
  | messages
    |help.rs
    | usage.rs

Actually that's the true structure but I have more files/dirs. So I want to use the "help.rs" and "usage.rs" in both the "main.rs" and "commons.rs" files. When trying to use "commons.rs" in "main.rs", I can just use: mod commons because they are in the same directory and it works. I thought about using: mod messages::help and mod messages::usage to import them but it doesn't work as expected. Any ideas?

1 Like

You only need the mod declaration in one place, from the parent module, and then other places can use the path to that module. I think this chapter of the book will help you:

https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html

The book doesn't refer about how to use subdirectories (unless I'm blind) inside "src" however. Luckily I was able to find how to do it thanks to this video. Thanks a lot for your time and have an amazing day

7.5 in particular does talk about file and directory layout.

It does but again, it doesn't contain info about how to create subdirectories and that you need to have a "mod.rs" file in the subdirectory and you also have to include any module publicly in this file. If I remember correctly, the book doesn't specify that you only have to declare a module only in the root source file and you don't have to do it in any other file in the directory. The book can indeed improve and I will probably contribute one time when I have free time

1 Like

True, this seems like a pretty big omission.

Ah, I missed that about your original example. You can use either messages.rs or messages/mod.rs, and that does need mod declarations for the submodules in messages/.

1 Like

I don't blame them of course. I really appreciate the fact that that they spend their free time for the community. I will probably contribute when I have free time

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.