cleancode.in

Clean code in Rust

The Rust Style Guide: types in UpperCamelCase, functions and variables in snake_case, constants in SCREAMING_SNAKE_CASE, 4 spaces a level and lines of 100 characters at most; rustfmt takes the guide as its default.

What does the Rust Style Guide ask for?

  • Prefer to use Rust’s expression oriented nature where possible; source

From The Rust Style Guide, advice.

How should Rust code look?

  • Four spaces a level. source
  • Lines of 100 characters at most. source
  • rustfmt follows the guide. source

What else does it ask?

How are names written in Rust?

KindExampleRule
TypesShoppingCartTypes in UpperCamelCase. source
Functionsadd_itemFunctions and methods in snake_case. source
Variablesitem_countLocal variables in snake_case. source
ConstantsMAX_ITEMSConstants in SCREAMING_SNAKE_CASE. source

What does cleaner Rust look like?

Before
const maxRetries: u32 = 3;
struct http_client { retryCount: u32 }

fn shouldRetry(c: &http_client) -> bool {
    let r;
    if c.retryCount < maxRetries { r = true; } else { r = false; }
    return r;
}
After
const MAX_RETRIES: u32 = 3;

struct HttpClient {
    retry_count: u32,
}

fn should_retry(client: &HttpClient) -> bool {
    client.retry_count < MAX_RETRIES
}

What changed?

  • The constant in SCREAMING_SNAKE_CASE, the type in UpperCamelCase. source
  • The function, the field and the argument in snake_case. source
  • The comparison is the function’s value: no temporary, no if, no return. source