design-patterns-rust
Design Patterns in Rust
Apply these patterns when designing or refactoring Rust code. Many GoF patterns translate differently in Rust due to ownership, enums, traits, and lack of inheritance. Distilled from the Rust Design Patterns book (rust-unofficial/patterns): idioms are the community's social norms — break them only with a good reason; patterns solve recurring problems; anti-patterns look helpful but cause more problems. Always favor why you reach for a pattern over how to spell it.
IDIOMS (social norms)
Foundational habits that make Rust code idiomatic. Prefer these before reaching for a named pattern.
Borrowed types for arguments
Take the most general borrow. Prefer &str over &String, &[T] over &Vec<T>, &T over &Box<T> — callers with either form can pass in, and you avoid a layer of indirection.
fn count_words(text: &str) -> usize { text.split_whitespace().count() } // not &String
Concatenate with format!
For building a string from pieces, format! reads better than a chain of push_str/+. Use push_str only in a hot loop where the extra allocation matters.