Rust code must adhere to the official style guide enforced by rustfmt, which automatically formats code to a consistent standard, while naming conventions follow strict camelCase for functions/variables and PascalCase for types. You should run cargo fmt before every commit to ensure compliance and rely on the compiler's clippy lints to catch naming inconsistencies.
The formatting tool rustfmt handles indentation, line breaks, and spacing, so you should not manually format code. For naming, use snake_case for functions, variables, and modules, PascalCase for types (structs, enums, traits), and SCREAMING_SNAKE_CASE for constants.
Here is a practical example of correct naming and a snippet showing how to enforce formatting:
// Correct naming conventions
const MAX_CONNECTIONS: u32 = 100; // Constants: SCREAMING_SNAKE_CASE
struct UserConfig { // Types: PascalCase
username: String, // Fields: snake_case
is_active: bool,
}
fn process_user_data(config: &UserConfig) -> Result<(), Error> { // Functions: snake_case
let user_name = config.username.clone();
if config.is_active {
// Logic here
}
Ok(())
}
To enforce these rules in your project, add the following to your .cargo/config.toml or simply run the commands manually. The rustfmt command reformats your code, while clippy checks for idiomatic Rust usage, including naming violations.
# Format the entire project to match the style guide
cargo fmt
# Run lints to check for style and naming issues
cargo clippy -- -W clippy::naming_conventions
If you need to configure specific formatting rules, create a rustfmt.toml in your project root. For example, to set a maximum line width of 100 characters:
# rustfmt.toml
max_width = 100
edition = "2021"
Remember that snake_case is mandatory for all non-type identifiers. Using camelCase for a function like getUserData will trigger a clippy::naming_conventions warning. Similarly, naming a struct userConfig instead of UserConfig is incorrect. The Rust community treats these conventions as strict rules rather than suggestions because they significantly improve code readability and tooling support. Always let the tooling handle the heavy lifting; manual formatting often leads to drift and merge conflicts in team environments.