How to split my code in different files?


So I am working on my Rust Actix-project and I'm really close to finishing it up - It was AWESOME to do web-programming in Rust.
But until now I have put all of my Rust code into one file.

This because I don't really understand the concepts of modules in Rust.
In another language I'd put each class or struct in its own class in a folder called domain. I'd put all functions with high cohesion or coupling it their own file.

But I have no clue on how to do this in Rust. In I for example have the module data. This contains all the logic to do CRUD-operations on the database.
I tried making another file and in my I tried the following on the top of my file:

pub mod data;
use crate::data;

Resulting in a lot of 'can't finds'.


use crate::data;

Resulting in

unresolved import `crate::data` no `data` in the root

The code is kinda getting too long to be manageable in one file. So I'd at least like to split all the modules now in in a different file. And I'd also like to put all the structs who belong together in a separate file.

I have my file here:

It won't compile because you don't have the remaining parts of the project. But I just include it to give you an insight in my code. I also don't expect a full solution, just a very minimal example would be sufficient. The one I find on Google are not working for my situation.


mod works exactly the same way as struct, enum, and fn — creates a new named item in the file where you put it.

You wouldn't write struct Foo {}; use Foo;. For the same reason once mod foo; is defined, you don't use it in the same file, and you don't redefine it elsewhere.

So what is the correct way? I have copied pub struct data {...} into a file called What do I type on the top of my

mod data; should work, as long as and are in the same directory. It is equivalent to this code:

mod data {
   // contents of

So if there is a pub struct data { ... } inside that module, its full path is now crate::data::data. You can refer to it by its full path, or you can write use crate::data::data; and then refer to the struct as just data. Here's a simple example in the playground.

If this is not working, please paste the full error you are getting, and the actual code that the error refers to. The code that you shared does not have mod data or crate::data anywhere, so it doesn't match the error that you shared.

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.