Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

2.16 Code Conventions and Formatting

The Rust community follows fairly standardized code style and naming conventions, largely enforced by tooling.

2.16.1 Formatting (rustfmt)

  • Indentation: 4 spaces (not tabs).
  • Tooling: rustfmt is the official tool for automatically formatting Rust code according to the standard style. Running cargo fmt applies it to the entire project. Consistent formatting enhances readability across different projects.

2.16.2 Naming Conventions

  • snake_case: Variables, function names, module names, crate names (e.g., let my_variable, fn calculate_sum, mod network_utils).
  • PascalCase (or UpperCamelCase): Types (structs, enums, traits), type aliases (e.g., struct Player, enum Status, trait Drawable).
  • SCREAMING_SNAKE_CASE: Constants, static variables (e.g., const MAX_CONNECTIONS, static DEFAULT_PORT).

2.16.3 Comparison with C

C style conventions vary significantly between projects and organizations (e.g., K&R style, Allman style, GNU style). While tools like clang-format exist, there isn’t a single, universally adopted standard quite like rustfmt in the Rust ecosystem.