Code Formatting and Rust Best Practices

About This Module

This module focuses on code formatting, readability, and best practices in Rust programming. Students will learn about the importance of clean, readable code and how to use Rust's built-in formatting tools. The module covers rustfmt, code style guidelines, and techniques for writing maintainable code that follows Rust community standards.

Prework

Before this lecture, please read:

Pre-lecture Reflections

  1. Why is consistent code formatting important in team development?
  2. How might automated formatting tools improve code quality and developer productivity?
  3. What are some examples of code that is technically correct but difficult to read?

Lecture

Learning Objectives

By the end of this lecture, you should be able to:

  • Use rustfmt to automatically format Rust code
  • Understand Rust community style conventions
  • Write readable and maintainable code
  • Apply refactoring techniques to improve code clarity
  • Configure and customize formatting tools for your development workflow

Don't give up on code formatting!

  • Rust doesn't require any specific indentation
  • Still a good idea to make your code readable
//This is bad code 
fn h(z:i32)->i32{
     let mut t=0.max(z.min(1)-0.max(z-1));
     for y in 1..=2.min(z){
         t+=h(z-y)
     }
     t
}
//This is even worse code 
fn g(z:i32)->i32{let mut t=0.max(z.min(1)-0.max(z-1));for y in 1..=2.min(z){t+=g(z-y)}t}
// This is good code
fn f(z:i32)->i32 {
    let t;
    if z==0{
        t = 0;
    } else if z == 1 {
        t = 1;
    } else {
        t = f(z-1) + f (z-2);
    }
    t
}
for i in 0..10 {
    println!("{}:{},{},{}",i,h(i),g(i),f(i));
};
0:0,0,0
1:1,1,1
2:1,1,1
3:2,2,2
4:3,3,3
5:5,5,5
6:8,8,8
7:13,13,13
8:21,21,21
9:34,34,34

Tool for formatting Rust code: rustfmt

  • If you have Rust installed, you should already have it.

  • rustfmt [filename] replaces the file with nicely formatted version

    • use rustfmt --backup [filename] to save the original file
  • rustfmt --help: see the command line parameters

  • rustfmt --print-config default: default config that can be adjusted

Other style tips:

  1. If you repeat sections of code, move it to a function
  2. If you have many if, else if, ... --> move it to a match statement
  3. if the body of a match variant is large, move content to a function...
  4. ...