-
Notifications
You must be signed in to change notification settings - Fork 0
Rust Coding Standards
Metrolla has adopted the Google style guide for Rust development.
Google's coding standards for Rust can be found in the Rust repository that Google maintains. While Google follows many of the community conventions, there are specific guidelines and recommendations that they adhere to for maintaining consistency and quality in their Rust code.
Here's a summary of the key points from Google's Rust coding standards:
- Clarity and Simplicity: Write clear and simple code. Prefer readability over cleverness.
- Consistency: Follow existing code conventions and structures.
-
Naming Conventions:
- Use
snake_casefor variables, functions, and module names. - Use
CamelCasefor type names, traits, and enums. - Use
ALL_CAPSfor constants and statics.
- Use
-
Comments:
- Use
///for documentation comments. - Use
//for inline comments. - Use
//!for module-level documentation.
- Use
- Indentation: Use 4 spaces per indentation level.
- Line Length: Limit lines to 100 characters.
-
Braces:
- Place opening braces on the same line as the statement (
fn,if, etc.). - Place closing braces on their own line unless followed by
elseor a similar construct.
- Place opening braces on the same line as the statement (
-
Whitespace:
- Use a single blank line to separate logical sections of code.
- Avoid trailing whitespace at the end of lines.
- Prefer using
ResultandOptiontypes for error handling. - Use
expectandunwrapsparingly and only when you are certain the operation cannot fail.
- Write tests for all new features and bug fixes.
- Use
#[test]attribute for unit tests. - Use
assert!,assert_eq!, and similar macros for assertions.
- Document all public items (functions, structs, traits, etc.).
- Include examples in documentation comments where appropriate.
- Use
rustdocfor generating documentation.
Here’s an example of how you might format a simple Rust module following these standards:
/// A module for handling simple arithmetic operations.
pub mod arithmetic {
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// let result = arithmetic::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// Subtracts the second number from the first number.
///
/// # Examples
///
/// ```
/// let result = arithmetic::subtract(5, 3);
/// assert_eq!(result, 2);
/// ```
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_subtract() {
assert_eq!(subtract(5, 3), 2);
}
}
}This example demonstrates clear naming conventions, proper documentation, and formatting in line with Google's standards.
For the most detailed and updated version of Google's Rust coding standards, you can refer to the documentation in their repositories or internal style guides if you have access.