1.9 KiB
1.9 KiB
Rust Style Guide
General
- Formatting: Always use
rustfmtwith default settings. - Linting: Use
clippyto catch common mistakes and improve code quality. Address all warnings. - Edition: Use the latest stable edition (currently 2024).
Naming Conventions
- Crates:
snake_case(e.g.,my_crate) - Modules:
snake_case(e.g.,my_module) - Types (Structs, Enums, Traits):
UpperCamelCase(e.g.,MyStruct) - Functions & Methods:
snake_case(e.g.,my_function) - Variables:
snake_case(e.g.,my_variable) - Constants:
SCREAMING_SNAKE_CASE(e.g.,MAX_SIZE) - Generics:
UpperCamelCase, usually single letters (e.g.,T,U) or descriptive names (e.g.,Input,Output).
Code Structure
- Imports: Group imports by crate. Use
stdfirst, then external crates, then internal modules. - Visibility: Minimizing visibility is preferred. Use
pub(crate)orpub(super)where appropriate. - Error Handling:
- Prefer
Result<T, E>overpanic!. - Use the
?operator for error propagation. - Use
anyhowfor application-level error handling andthiserrorfor library-level errors.
- Prefer
Documentation
- Public API: Document all public items using
///comments. - Module Level: Include module-level documentation using
//!at the top of the file. - Examples: Include examples in documentation where helpful.
Testing
- Unit Tests: Place unit tests in a
testsmodule within the same file, annotated with#[cfg(test)]. - Integration Tests: Place integration tests in the
tests/directory at the crate root.
Idioms
- Pattern Matching: Use pattern matching (
match,if let) extensively. - Ownership & Borrowing: Follow Rust's ownership rules strictly. Avoid
clone()unless necessary. - Iterators: Prefer iterators and combinators (
map,filter,fold) over explicit loops.