Rust Refactor Best Practices
Architectural refactoring guide for Rust applications. Contains 91 rules across 10 categories, prioritized by impact from critical (type safety, ownership) to incremental (iterator idioms).
When to Apply
Refactoring existing Rust codebases or planning large-scale restructuring
Reviewing PRs for architectural issues and code smells
Designing type-safe APIs with proper error handling
Organizing Rust project structure with Cargo workspaces
Improving module boundaries and visibility control
Applying consistent naming conventions (RFC 430)
Replacing stringly-typed APIs with strong types
Rule Categories
Category
Impact
Rules
Key Topics
Type Safety & Patterns
CRITICAL
20
Newtypes, typestate builders, PhantomData, enums, trait objects, associated types
Ownership & Borrowing
CRITICAL
6
Borrowing, Cow, lifetime elision, clone avoidance
Error Handling
HIGH
15
thiserror/anyhow, two-tier strategy, context, graceful degradation
API Design & Traits
HIGH
6
Sealed traits, extension traits, generic bounds, builder pattern
Project Organization
HIGH
6
Cargo workspaces, crate separation, feature grouping
Module & Visibility
MEDIUM-HIGH
9
Re-exports, visibility control, test co-location, module splitting
Naming Conventions
MEDIUM-HIGH
13
RFC 430, snake_case, PascalCase, predicates, unit suffixes
Conversion Traits
MEDIUM
5
From/Into, AsRef, TryFrom, Deref
Idiomatic Patterns
MEDIUM
6
Default, let-else, destructuring, match guards
Iterator & Collections
LOW-MEDIUM
5
Iterator methods, collect turbofish, filter_map
Quick Reference
Critical patterns
— get these right first:
Use newtype patterns to prevent unit confusion and encode invariants
Prefer borrowing over ownership in function parameters
Use thiserror for library errors, anyhow for application errors
Use typestate builders for compile-time required field enforcement
Common mistakes
— avoid these anti-patterns:
Stringly-typed APIs instead of strong types
Unnecessary clone calls when borrowing would work
panic! for recoverable errors instead of Result
Over-exposing internal types with pub visibility
Table of Contents
Type Safety & Patterns
—
CRITICAL
1.1
Encode Invariants in Newtype Constructors
— CRITICAL
1.2
Use Newtype Pattern for Unit Safety
— CRITICAL
1.3
Replace Stringly-Typed APIs with Strong Types
— CRITICAL
1.4
Use Non-Exhaustive for Extensible Enums
— CRITICAL
1.5
Use PhantomData for Type-Level State
— CRITICAL
1.6
Use Typestate Builders for Required Fields
— CRITICAL
1.7
Use Associated Types for Related Type Relationships
— HIGH
1.8
Use Enums for Type-Safe Variants
— HIGH
1.9
Use Option for Nullable Fields
— HIGH
1.10
Use async_trait for Async Trait Methods
— MEDIUM
1.11
Use bitflags! for Type-Safe Bit Flags
— MEDIUM
1.12
Use Box for Runtime Polymorphism
— MEDIUM
1.13
Use Builder Pattern with Method Chaining
— MEDIUM
1.14
Derive Copy for Simple Enums
— MEDIUM
1.15
Implement Operator Traits for Domain Types
— MEDIUM
1.16
Use PhantomData for Unused Generic Parameters
— MEDIUM
1.17
Use Public Fields for Data Structs
— MEDIUM
1.18
Use Consistent Derive Order for Data Structs
— MEDIUM
1.19
Group Related Trait Implementations Together
— LOW
1.20
Use Type Aliases for Complex Generics
— LOW
Ownership & Borrowing
—
CRITICAL
2.1
Accept Borrowed Types Over Owned References
— CRITICAL
2.2
Avoid Unnecessary Clone Calls
— CRITICAL
2.3
Use Cow for Conditional Ownership
— CRITICAL
2.4
Leverage Lifetime Elision Rules
— CRITICAL
2.5
Prefer Borrowing Over Ownership in Function Parameters
— CRITICAL
2.6
Return Owned Types for Caller Flexibility
— CRITICAL
Error Handling
—
HIGH
3.1
Use Two-Tier Error Strategy
— HIGH
3.2
Use thiserror for Custom Error Types
— HIGH
3.3
Use anyhow for Application Error Handling
— HIGH
3.4
Use Result Instead of panic! for Recoverable Errors
— HIGH
3.5
Reserve panic! for Unrecoverable Situations
— HIGH
3.6
Include Path Context in IO Errors
— HIGH
3.7
Use Option for Absence, Not Sentinel Values
— HIGH
3.8
Use the Question Mark Operator for Error Propagation
— HIGH
3.9
Use context() and with_context() for Error Messages
— MEDIUM
3.10
Use bail! for Validation Failures
— MEDIUM
3.11
Use Graceful Degradation for Non-Critical Operations
— MEDIUM
3.12
Use #[source] for Error Chaining
— MEDIUM
3.13
Use expect() with Descriptive Messages
— LOW
3.14
Use ok_or_else for Expensive Error Construction
— LOW
3.15
Define Module-Local Result Type Alias
— LOW
API Design & Traits
—
HIGH
4.1
Derive Common Traits for Public Types
— HIGH
4.2
Implement Standard Traits for Ergonomic APIs
— HIGH
4.3
Use Trait Bounds for Generic Flexibility
— HIGH
4.4
Use Sealed Traits to Prevent External Implementation
— HIGH
4.5
Use Builder Pattern for Complex Construction
— HIGH
4.6
Use Extension Traits to Add Methods to Foreign Types
— HIGH
Project Organization
—
HIGH
5.1
Use Cargo Workspace for Multi-Crate Projects
— HIGH
5.2
Use snake_case for All Directory Names
— HIGH
5.3
Separate Binary and Library Crates
— HIGH
5.4
Group Crates by Feature Domain
— MEDIUM
5.5
Use Dedicated Common Crate for Shared Utilities
— MEDIUM
5.6
Keep Crate Structure Flat
— MEDIUM
Module & Visibility
—
MEDIUM-HIGH
6.1
Use Explicit Module Declarations in lib.rs
— HIGH
6.2
Co-locate Tests as test.rs Files
— HIGH
6.3
Minimize Public API Surface
— MEDIUM-HIGH
6.4
Use pub use for Clean Module Re-exports
— MEDIUM-HIGH
6.5
Split Large Modules into Submodules
— MEDIUM-HIGH
6.6
Use crate Prefix for Internal Imports
— MEDIUM-HIGH
6.7
Use tests Submodule for Unit Tests
— MEDIUM-HIGH
6.8
Use cfg Attributes for Conditional Modules
— MEDIUM
6.9
Separate Types and Errors into Dedicated Files
— MEDIUM
Naming Conventions
—
MEDIUM-HIGH
7.1
Use snake_case for Functions and Methods
— HIGH
7.2
Use PascalCase for Types
— HIGH
7.3
Use snake_case for Module Names
— HIGH
7.4
Use new for Constructors
— HIGH
7.5
Use SCREAMING_SNAKE_CASE for Constants
— MEDIUM
7.6
Prefix Getter Functions with get_
— MEDIUM
7.7
Use is_, has_, should_ for Boolean Predicates
— MEDIUM
7.8
Use to_ and from_ for Conversions
— MEDIUM
7.9
Use Descriptive Suffixes for Type Specialization
— MEDIUM
7.10
Include Unit Suffixes in Field Names
— LOW
7.11
Use Descriptive or Single-Letter Generic Parameters
— LOW
7.12
Use Single Lowercase Letters for Lifetimes
— LOW
7.13
Name Test Files as test.rs
— LOW
Conversion Traits
—
MEDIUM
8.1
Implement From Instead of Into
— MEDIUM
8.2
Accept AsRef for Flexible String Parameters
— MEDIUM
8.3
Implement Deref for Transparent Newtype Access
— MEDIUM
8.4
Use TryFrom for Fallible Conversions
— MEDIUM
8.5
Use Inner Function Pattern to Reduce Monomorphization
— MEDIUM
Idiomatic Patterns
—
MEDIUM
9.1
Implement Default Instead of new() Without Arguments
— MEDIUM
9.2
Follow Constructor Naming Conventions
— MEDIUM
9.3
Use let-else for Early Returns on Pattern Match Failure
— MEDIUM
9.4
Use Struct Update Syntax for Partial Overrides
— MEDIUM
9.5
Use Destructuring for Multiple Returns and Field Access
— MEDIUM
9.6
Use Match Guards for Complex Conditions
— MEDIUM
Iterator & Collections
—
LOW-MEDIUM
10.1
Prefer Iterator Methods Over Manual Loops
— LOW-MEDIUM
10.2
Use Turbofish for Explicit collect Type
— LOW-MEDIUM
10.3
Use filter_map for Combined Filter and Transform
— LOW-MEDIUM
10.4
Avoid Collecting Then Iterating
— LOW-MEDIUM
10.5
Use enumerate Instead of Manual Index Tracking
— LOW-MEDIUM
References
https://rust-lang.github.io/api-guidelines/
https://rust-unofficial.github.io/patterns/
https://doc.rust-lang.org/book/
https://www.lurklurk.org/effective-rust/
https://rust-lang.github.io/rust-clippy/