3 ways to break your Rust code into modules [video]

0
2973
2 min read

“Idiomatic coding means following the conventions of a given language. It is the most concise, convenient, and common way of accomplishing a task in that language, rather than forcing it to work in a way the author is familiar with from a different language.” – Adapted from Tim Mansfield

Idiomatic rust code is beneficial for both the users of your code when you write and package it as libraries and also to build your own applications. One of the methods of writing elegant and concise rust code is to break up the code into modules.

This clip is taken from the course Learning Rust by Leo Tindall. With this course, you will learn to write fast, low-level code in Rust.

Breaking code helps in improving readability and discovery of code and documentation for both you and other contributors–if you are working on a project with multiple people.

Breaking up codes is important because:

  • The code can be functionally separate.
  • People can figure out how the code base is structured without them going through the documentation.

The best way to break up codes is by functional units. Each module should export a few symbols but lots of cross-coupling is a bad sign.

Use module-per-struct

If you have a lot of complex structs, it can be useful to make multiple sub-modules for each struct. This is also applicable to other implementations such as enums. All implementations for these structs should be in their module. The module root can then re-export them in a flat way.

Avoid Cross-coupling

Cross-coupling between modules and especially between levels is a ‘Code Smell’ or a symptom of bad design. You should use visibility modifiers to control access to implementations only where they are needed.

Testing In-module

For many architectures testing within each module is sufficient for unit testing. However, if necessary, depending on an organization, tests can be placed in a sub-module, generally in the same file.

Watch the video to walk through each of the methods in detail. If you liked the video, don’t forget to check out the comprehensive course Learning Rust, packed with step-by-step instructions, working examples, and helpful tips and techniques on working with Rust.

About the author

Leo Tindall is a software developer and hacker from San Diego whose interests include scalability, parallel software, and machine learning.

Read Next

9 reasons why Rust programmers love Rust

Rust as a Game Programming Language: Is it any good?

Rust 2018 RC1 now released with Raw identifiers, better path clarity, and other changes

Content Marketing Editor at Packt Hub. I blog about new and upcoming tech trends ranging from Data science, Web development, Programming, Cloud & Networking, IoT, Security and Game development.