Modules and imports

Hello, I'm a developer coming from javascript and I'm having a hard time understanding modules and imports in rust. I have this file structure:
And I'm getting this error when trying to import the services functions in controllers:

The only way that I finded to the error disappear is putting "mod services;" in But I want that only the controllers to see the services module. Has someway to do that?

To achieve that, you must put mod services inside the controllers module, and services/ within controllers/. Rust has no “friend” access; an item (module, function, type, etc.) is always visible to the module in which is declared and in all children of it.

If you don't require that strict privacy and want to keep your current hierarchy, then writing mod services; in is the correct solution.

I see, isn't it considered bad practice for the software architecture to make all modules visible in Because this seems to be in some way violating the principle of single responsibility

No matter what programming language you use, and how you structure your program, there will always be properties that are important to the architecture, that you can't enforce by means of program structure. It's up to you to decide whether this property is important vs. other properties your program could have. If you feel it is, then all you have to do is arrange the module hierarchy as I described: define the services module inside the controllers module.

(It is possible to arrange the module hierarchy separately from the file hierarchy, but don't do that; it makes it harder for other Rust developers to read your program.)

1 Like

Not all modules are visible to main. What's happening here is that you have to declare a module with mod, or the compiler won't know about it. The way you have structured your folders is such that you have to put the mod for services in main for it to refer to the correct file/folder. This makes services a submodule of main, and the parent module can always see its child modules. If you however move services inside controllers then you'll be able to declare it (with mod) inside controllers/, making it a submodule of the controllers module and main won't have access to it unless you make it pub or you pub use it or some parts of it.


This is a software architecture question and mostly independent of the language. See project structure - Folder-by-type or Folder-by-feature - Software Engineering Stack Exchange

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.