Splitting up modules in Rust


A few weeks ago, I decided to prioritize learning Rust over a few other potential side projects. I had played around with the language a few times in past but I never learned anything too in-depth. Learning a new programming language is a great way to expand your perspective and I’ve heard a lot of really good things about Rust.
My project is a fairly basic service that accepts TCP connections using RESP, does a bit of optimization for types, and dumps the data into a HashMap. Nothing too special but it does allow me to learn a wide range of concepts. Smooth sailing so far!
After an hour or two of coding, I realized my two projects files, main.rs and lib.rs, were getting large and unwieldy. My mind couldn’t really process the sheer size of these files and I was spending a lot of time searching for the structs I needed. It was probably time to break these apart.
I did some searching in the Rust docs and Stack Overflow. After a few minutes I found some posts on breaking up your code by doing the following.
Then add this code to lib.rs to make them accessible to main.rs.
There wasn’t even a need to wrap the contents of each file in pub mod! That makes my code feel so much cleaner and I don’t have to worry about everything being indented another 4 spaces to the right. As a developer who cares about code aesthetics, this makes me very happy.
Fast forward a few more days and I realized that types/mod.rs was getting unwieldy. The code was more complex and I was breaking things out into smaller structs. I needed to simplify.
Here’s how the next 30 minutes went: 🤔 😕 😨 😠
The documentation wasn’t entirely helpful. There were a number of posts on the Rust subreddit and Stack Overflow, but they only seemed to cover the basics of going from main.rs and lib.rs to using folders beyond mod.rs.
I could have created more folders and broken things out horizontally, but that felt dirty. Some of my sub-structs were “private” in nature. It didn’t seem right to expose them at the top-level of my whole project. There had to be a better solution. Rust couldn’t be this naive.
After digging a bit deeper and looking at how other projects solved this problem, I was able to figure out a solution!
For example, my types folder would look like this.
Then src/types/mod.rs would contain the following.
Finally, I can write all my code in files like qarray.rs, qinteger.rs, and qstring.rs!


So… what did we really learn from all this?
Continuously learning is an important part of our careers and finding the right answer isn’t always a straightforward path. Occasionally documentation has some holes or a language has rough edges. Instead of taking to Twitter to complain about an ecosystem being immature or naive, spend a bit of time learning how to make things better and find a more correct solution to your problems.
Bonus points if you try and share your knowledge with others! 😄