chapter five

5 Cleanup your codebase

 

This chapter covers

  • Grouping your functions into different modules.
  • Splitting your modules into different files.
  • Creating a practical folder structure within your Rust project.
  • Understanding the difference between doc comments and hidden comments.
  • Adding example code in your comments and testing it.
  • Using clippy to lint your code.
  • Using cargo to format and compile your codebase.

Rust comes equipped with a large set of tools which makes it easy to organize, structure, test and comment it. The ecosystem values good documentation style which is the reason why Rust has a built-in commenting system which generates code documentation on the fly, and even tests the code in your comments so your documentation is never out-of-date.

There is also a widely supported linter called clippy, which is the de facto standard in the Rust world. It comes with many pre-set rules and helps to point out best-practices or missing implementations. In addition, Rust’s package manager cargo helps auto-format your code based on pre-defined rules.

In the previous chapter, we built out different API routes for our Q&A applications, extracted information out of URL parameters and, most importantly, added our own structures and error implementations and handling. We all added this into the main.rs file, which grew with every route handler we added.

5.1 Modularize your code

5.1.1 Using Rusts built-in mod system

5.1.2 Practical folder structure for different use cases

5.1.3 Creating libraries and sub-crates

5.2 Document your code

5.2.1 Using doc comments and private comments

5.2.2 Adding code in your comments

5.3 Linting and formatting your codebase

5.3.1 Installing and using Clippy

5.3.2 Formatting your code with rustfmt

5.4 Summary