Write idiomatic, high-quality Rust code following community best practices. Use when writing, reviewing, or refactoring Rust code (.rs files, Cargo.toml), converting code to Rust, designing error types with Result/Option, implementing traits, or when discussing ownership, borrowing, lifetimes, or Rust API design patterns.
Instrucciones de origen · Vista previa de solo lectura
name
idiomatic-rust
description
Write idiomatic, high-quality Rust code following community best practices. Use when writing, reviewing, or refactoring Rust code (.rs files, Cargo.toml), converting code to Rust, designing error types with Result/Option, implementing traits, or when discussing ownership, borrowing, lifetimes, or Rust API design patterns.
Idiomatic Rust
This skill provides guidance for writing idiomatic Rust code that follows community conventions, leverages the type system effectively, and produces maintainable, performant software.
Core Principles
1. Leverage the Type System
Rust's type system is your greatest ally. Use it to:
Make invalid states unrepresentable - Design types so illegal combinations cannot compile
Encode invariants at compile time - Use newtypes, enums, and const generics
Prefer From/TryFrom over as casts - Explicit, safe conversions
Document the "why", not the "what" - Code shows what, comments explain why
Include examples in doc comments - They're tested by cargo test
Document panics, errors, and safety - Required sections for public APIs
Use #[doc(hidden)] for internal public items
/// Parses a configuration file from the given path.////// # Errors////// Returns an error if the file cannot be read or contains invalid TOML.////// # Examples////// ```/// let config = parse_config("config.toml")?;/// assert_eq!(config.name, "my-app");/// ```pubfnparse_config(path: &str) ->Result<Config, ConfigError> { ... }
Quick Reference
Naming Conventions (RFC 430)
Item
Convention
Example
Crates
snake_case
my_crate
Modules
snake_case
my_module
Types
UpperCamelCase
MyStruct
Traits
UpperCamelCase
MyTrait
Enum variants
UpperCamelCase
MyVariant
Functions
snake_case
my_function
Methods
snake_case
my_method
Local variables
snake_case
my_variable
Static variables
SCREAMING_SNAKE_CASE
MY_STATIC
Constants
SCREAMING_SNAKE_CASE
MY_CONST
Type parameters
UpperCamelCase, short
T, E, K, V
Lifetimes
lowercase, short
'a, 'de, 'src
Conversion Method Prefixes
Prefix
Cost
Ownership
Example
as_
Free
Borrowed → Borrowed
fn as_str(&self) -> &str
to_
Expensive
Borrowed → Owned
fn to_string(&self) -> String
into_
Variable
Owned → Owned
fn into_inner(self) -> T
Getter/Setter Conventions
// GOOD: No get_ prefix for gettersimplFoo {
fnbar(&self) -> &Bar { &self.bar }
fnbar_mut(&mutself) -> &mut Bar { &mutself.bar }
fnset_bar(&mutself, bar: Bar) { self.bar = bar; }
fninto_bar(self) -> Bar { self.bar }
}