Rust Conventions And Such

Code Formatting

In rust, we use both snake_case and PascalCase. They serve different purposes.

  • Variables and function names are typically snake case
  • Module names are typically use snake_case
  • Struct, enums, and trait names are typically written in PascaleCase.
  • SCREAMING_SNAKE_CASE is used for constants and static variables.

Deriving Traits

This is commonly seen in rust codebases. Use #[derive] to automatically implement traits like Clone, Debug, PartialEq, etc., for your types.

  #[derive(Debug, Clone, PartialEq)]
  struct MyStruct {
      field1: i32,
      field2: String,
  }

Breakdown:

  • derive is a macro for composing traits
  • Debug is used for formatting a value using the {:?} formatter in println! and similar macros
  • PartialEq trait allows for the comparison of objects for equality using the == and != operators. AKA, allows comparing fields for value not just identity.
  • Clone trait allows for the explicit duplication of an object. When you add this trait, the struct automatically gets a clone method that creates a deep copy of the instance.

Clippy

clippy is a commonly used rust linter. Use it.

cargo clippy
end of storey Last modified: