Rust Code Guidelines
Aug 08, 2021
Dec 20, 2023
Follow these standards to maintain consistency, readability, and best practices across our Rust projects.
Table of Contents
- Table of Contents
- Naming Conventions
- Formatting
- Documentation
- Error Handling
- Ownership and Borrowing
- Pattern Matching
- Concurrency
- Testing
Naming Conventions
- Use snake_case for function and variable names.
- Use CamelCase for struct, enum, and trait names.
- Use SCREAMING_SNAKE_CASE for constants.
- Be descriptive and avoid abbreviations when naming.
Formatting
- Use four spaces for indentation.
- Limit lines to 100 characters.
- Use a space after commas and colons.
- Place opening braces on the same line as the function/struct/trait definition.
Documentation
- Document all public functions, structs, enums, and traits.
- Use
///
for documenting functions,//!
for documenting modules.
/// Adds two numbers together.
///
/// # Arguments
///
/// * `a` - The first number
/// * `b` - The second number
///
/// # Returns
///
/// The sum of the two numbers.
Error Handling
- Prefer using the
Result
type for functions that may return an error. - Use the
?
operator for concise error propagation.
Ownership and Borrowing
- Follow the ownership and borrowing principles to prevent data races and memory issues.
- Use borrowing (
&
) when possible to avoid unnecessary ownership transfer.
Pattern Matching
- Use pattern matching to handle different cases concisely.
match some_result
Concurrency
- Use the
std::thread
module for basic concurrency. - For more advanced concurrency, consider using the
async/await
syntax with an async runtime.
Testing
- Write unit tests for each module and integration tests for the entire project.
- Use the
#[cfg(test)]
attribute for test-specific code.
These guidelines aim to ensure code consistency and readability, fostering a collaborative and efficient development environment. Happy coding in Rust!