LibCoder

Design Patterns and Best Practices in Rust: Enhance your Rust skills by applying idiomatic approaches to real-world software design

1C Agda Rust
Design Patterns and Best Practices in Rust: Enhance your Rust skills by applying idiomatic approaches to real-world software design
Автор: Williams Evan
Дата выхода: 2026
Издательство: Packt Publishing Limited
Количество страниц: 450
Размер файла: 1,9 МБ
Тип файла: PDF
Добавил: LibCoder
Оглавление
Design Patterns and Best Practices in Rust....2 Enhance your Rust skills by applying idiomatic approaches to real-world software design....2 Design Patterns and Best Practices in Rust....3 Foreword....5 Contributors....7 About the author....7 About the reviewers....8 Join us on Discord!....9 Table of Contents....10 Preface....20 Who this book is for....21 What this book covers....21 To get the most out of this book....23 Download the example code files....24 Download the color images....24 Conventions used....24 Get in touch....25 Free benefits with your book....26 How to Unlock....27 Share your thoughts....28 Part 1....30 Thinking in Rust....30 1....32 Why Is Rust Different?....32 Technical requirements....33 Why do I need new patterns?....33 Working with the familiar....33 Experience can be misleading....34 Example – parsing messages in place....35 Hitting the wall....39 A sudden stop....39 Learning why this happens....40 The Rust learning curve....43 Learning Rust can feel very different....43 The uneven path....43 Learning to think in Rust....45 Thinking in code....45 Finding understanding....45 Let's build a calculator, badly!....46 Summary....49 Get this book's PDF version and more....49 2....50 Anti-Pattern: Designing for Object Orientation....50 Technical requirements....51 Why is Rust not an OO language?....51 Structs are not classes....52 Rust has a different take on polymorphism....53 The borrow checker prevents object patterns....54 Pulling it together: types are not objects....55 Misusing traits....56 Using Deref as a poor substitute for inheritance....63 Attacking the mess....63 Can Deref help us?....65 Using generic types to act like classes....68 Using enums where they don't make sense....74 A "not-so-bad" calculator....74 A worse calculator....78 The worst calculator....80 Summary....82 Get this book's PDF version and more....83 3....84 Anti-Pattern: Using Clone and Rc Everywhere....84 Technical requirements....85 Avoiding ownership concerns....85 The allure of ignoring ownership....85 Why does ownership matter?....88 Cloning everything....90 The clone hammer....91 A better approach....93 Misusing Rc and RefCell (and friends)....95 The siren song of smart pointers....96 Simpler is better....98 When to use smart pointers....103 Summary....103 Get this book's PDF version and more....104 4....106 Don't Fight the Borrow Checker....106 Technical requirements....106 Trying to defeat the borrow checker: friend or foe?....107 unsafe is (usually) not the answer: a dangerous shortcut....114 Over-using globals and mutable statics....123 Summary....130 Get this book's PDF version and more....131 Part 2....132 Replacing Traditional Design Patterns....132 5....134 Creational Patterns: Making Things....134 Technical requirements....135 Factory Method....135 How does Factory Method work in Rust?....135 Beyond simple creation....140 Abstract Factory....147 Implementing Abstract Factory in Rust....147 When and when not to use Abstract Factory....154 Builder....155 Why use Builder?....155 Why use a specialized builder?....160 When not to use Builder....162 Singleton....162 Prototype....167 Summary....172 Get this book's PDF version and more....173 6....174 Structural Patterns: Connecting and Aggregating Components....174 Technical requirements....175 Proxies, decorators, and adapters....175 The Proxy pattern in Rust....175 The Decorator pattern: extensible expression behavior....176 Designing the Expression interface....177 Implementing expression decorators....178 The logging decorator....179 The timing decorator....180 The caching decorator with interior mutability....181 The range validating decorator....183 Composing and using decorators....183 The Adapter pattern: integrating external libraries....184 Designing and implementing adapters....185 When to use these patterns....189 Facades....190 The need for a unified interface....191 Designing the calculator facade....191 Implementing convenience methods....193 Rust alternatives: modules and crates as facades....194 When to use the Facade pattern....195 Composites....196 The challenge of hierarchical expressions....196 Designing leaf and composite nodes....197 Implementing function calls....200 Building and evaluating expression trees....201 When to use the Composite pattern....203 Flyweight....204 The Bridge....206 The challenge of multiple dimensions of variation....206 Designing the abstraction and implementation....207 Implementing concrete output mechanisms....208 A second bridge: evaluation strategies....210 When to use the Bridge pattern....212 Summary....213 Get this book's PDF version and more....214 7....216 Behavioral Patterns 1: Taking Action....216 Technical requirements....217 Command pattern: encapsulating operations....217 The need for operation management....217 Designing the command interface....218 Implementing concrete commands....219 Managing commands with a command processor....221 Using commands in the calculator interface....222 When to use the Command pattern....223 Chain of Responsibility: flexible input processing....223 The challenge of input processing....224 Designing the handler interface....224 Implementing concrete handlers....226 Building the chain....229 Extending the chain....230 When to use the Chain of Responsibility pattern....231 Strategy pattern: swappable algorithms....231 The challenge of multiple evaluation approaches....231 Designing the strategy interface....232 Implementing concrete strategies....233 Standard evaluation....233 Optimizing evaluation....234 Safe evaluation....234 Integrating strategies with the calculator....235 Using strategies in practice....236 Combining Strategy with the Command pattern....237 When to use the Strategy pattern....238 Mediator pattern: coordinating components....238 The challenge of component coordination....239 Designing the mediator interface....239 Components and mediator integration....241 The concrete mediator....243 Handling events....244 Providing unified access....246 Wiring everything together....246 When to use the Mediator pattern....247 Template Method pattern: structured algorithms....248 The challenge of algorithm standardization....248 Designing the template method trait....248 Common steps with default implementations....249 Required steps without defaults....250 Implementing concrete evaluators....251 Recursive descent evaluator....251 Shunting yard evaluator with custom validation....252 Specialized evaluators through composition....253 Integration with other patterns....254 When to use the Template Method pattern....255 Summary....255 Get this book's PDF version and more....257 8....258 Behavioral Patterns 2: Keeping Track....258 Technical requirements....259 Iterator pattern: efficient collection traversal....259 The need for collection iteration....260 Implementing a history iterator....261 Traversing expression trees....262 Implementing double-ended iterators....266 Integration with the calculator interface....268 When to use custom iterators....269 State pattern: changing behavior based on state....270 The need for modal behavior....270 Designing the state interface....271 Implementing concrete states....274 State transitions....277 When to use the State pattern....277 Memento pattern: capturing and restoring state....278 The need for state management....278 Designing the memento....279 Calculator as originator....280 The caretaker....281 Integrating with the calculator....283 Persistence with serialization....286 When to use the Memento pattern....287 Observer pattern: reacting to changes....287 The need for reactive components....287 Designing an event-based observer....288 Implementing the subject....289 Creating concrete observers....290 Integrating observers with the calculator....292 When to use the Observer pattern....294 Visitor pattern: separating algorithms from structure....294 The challenge of operating on expression trees....295 Designing the visitor interface....296 Implementing Visitable for expression types....297 Creating concrete visitors....298 Variable dependency collector....298 Expression optimizer....299 Using visitors in the calculator....301 When to use the Visitor pattern....303 Summary....304 Get this book's PDF version and more....305 Part 3....306 New Patterns for Rust....306 9....308 Architectural Patterns....308 Technical requirements....309 Data flows downward....309 Designing Samsa's data flow....309 Producer: sends data downward....312 Broker: manages flow direction....314 Consumer: only receives data....316 Storage: provides the foundational layer....318 The borrow checker enforces good design....320 Benefits of downward data flow....320 Mutability stays contained....320 Messages: immutable by design....320 Broker: controls mutations....321 Consumer: owns and isolates state....322 Benefits of contained mutability....323 Modules become interfaces....323 Public API structure....323 Storage interface....324 Benefits of module-based architecture....325 Pack lightly....325 The problem with heavy structures....325 Lightweight design....326 Zero-copy views....327 Benefits of lightweight design....328 Summary....328 Get this book's PDF version and more....330 10....332 Patterns That Leverage the Type System....332 Technical requirements....333 The NewType pattern....333 Identifying the problem....333 Implementing type-safe wrappers....334 Enhanced Samsa API....337 Parse, don't validate....339 The problem with scattered validation....339 Creating types that enforce validity....340 Builder pattern with validation....342 The TypeState pattern....345 The problem with runtime state management....346 Implementing TypeState for the consumer lifecycle....347 Usage examples....351 Sealed traits....353 The problem with open traits....353 Implementing the sealed traits pattern....354 Type-safe messages with sealed schemas....357 Summary....359 Get this book's PDF version and more....360 11....362 Patterns from Functional Programming....362 Technical requirements....363 Function pipelines....363 Generics as type classes: revisiting TypeState....367 Pattern matching patterns....374 Patterns using closures....380 Closure traits and capture semantics....381 Configurable message filters....381 Why closures instead of functions?....383 The Strategy pattern with closures....384 Processing pipelines with closures....387 Summary....389 Get this book's PDF version and more....390 12....392 Patterns Emerging from Rust's Core Features....392 Technical requirements....393 The Result and Option patterns....393 Configuration loading with error composition....394 The sequential fallback pattern....400 Processing with error collection....401 Patterns using blocks....404 RAII patterns in Rust....407 Elegance and conciseness....410 Summary....415 Get this book's PDF version and more....416 13....418 Leaning into Rust....418 Technical requirements....419 Use patterns natural to the language....419 What the Bad Calculator taught us....419 What the Correct Calculator taught us....420 What Samsa taught us....421 Recognizing natural patterns....421 Allow the language to help you....422 The borrow checker as design consultant....422 The type system as design tool....423 Error handling as first-class design....423 Ownership as automatic resource management....424 Tooling as a quality force multiplier....425 Compiler-driven development....425 Think in Rust....426 The mental shift: three projects, one lesson....426 Ownership as a design philosophy....427 Zero-cost abstractions as a mindset....427 Safety without paranoia....428 Composition over inheritance, naturally....429 Explicitness as a core value....430 From writing Rust to thinking in Rust....430 Summary....431 Get this book's PDF version and more....432 14....434 Unlock Your Exclusive Benefits....434 Unlock this Book's Free Benefits in 3 Easy Steps....435 Step 1....435 Step 2....435 Step 3....436 Need Help....436 Why subscribe?....438 Other Books You May Enjoy....439 Packt is searching for authors like you....442 Share your thoughts....442 Subscribe to Deep Engineering....443 Index....444

Описание

В этом материале разберём тему: rust.

Write safer, more maintainable Rust code by identifying anti-patterns, applying idiomatic design patterns tailored to ownership, borrowing, and the type system, and learning when to adapt or avoid traditional solutions.

Free with your book: DRM-free PDF version + access to Packt's next-gen Reader*

These mismatches often lead to confusing compiler errors, awkward workarounds, or brittle code. Key FeaturesLeverage traits, ownership, borrowing, and lifetimes to structure expressive, modular Rust codeAvoid common Rust anti-patterns and design pitfalls with clear, Rust-specific guidanceDesign practical Rust applications using Rust-native and adapted design patternsBook DescriptionMany Rust developers run into problems when they try to apply familiar object-oriented or cross-language patterns to Rust projects. This book helps you avoid those traps by thinking in Rust and applying idiomatic design patterns that embrace ownership, borrowing, and type safety.

From there, you’ll explore how to rethink traditional design solutions for Rust, including creational, structural, and behavioral design patterns. The book begins with anti-patterns and common mistakes Rust developers often encounter, including misusing object-oriented thinking, over-relying on Clone, or treating the borrow checker as an obstacle. You’ll also dive into architectural strategies, type-driven design, and Rust-specific techniques such as TypeState. The final chapter brings these ideas together into a design mindset rooted in idiomatic Rust.

By the end of this book, you’ll know how to avoid costly mistakes, apply effective patterns confidently, and design Rust applications that are clean, scalable, and reliable.

*Email sign-up and proof of purchase required

What you will learnDesign maintainable applications using idiomatic Rust patternsRecognize Rust anti-patterns that lead to messy or inefficient codeAdapt creational, structural, and behavioral design patterns to RustLeverage the type system to catch logic errors at compile timeStructure code effectively with modules, traits, and clear interfacesWork with ownership, borrowing, and the type system to simplify data handlingImplement functional techniques for clearer, expressive Rust codeWho this book is forRust developers ready to move beyond the basics and improve how they design and structure code will benefit from this book. If you're comfortable building simple applications and using tools like Cargo, this book will help you write cleaner, more idiomatic, and reliable software.

It’s ideal for those looking to understand which patterns work in Rust, how to avoid common traps, and how to tackle more complex, real-world projects with confidence.

Если материал оказался полезен — сохраните страницу.

rust design patterns book idiomatic type this code

Частые вопросы

Можно ли скачать «Design Patterns and Best Practices in Rust: Enhance your Rust skills by applying idiomatic approaches to real-world software design» бесплатно?

Да, «Design Patterns and Best Practices in Rust: Enhance your Rust skills by applying idiomatic approaches to real-world software design» доступна для бесплатного скачивания на нашем сайте в формате PDF. Ссылка на файл находится на этой странице.

В каком формате и какого размера файл?

Книга предоставляется в формате PDF, размер файла 1,9 МБ.

Кто автор и когда вышла книга?

автор — Williams Evan, издательство Packt Publishing Limited, год выпуска 2026, 450 страниц.

О чём книга «Design Patterns and Best Practices in Rust: Enhance your Rust skills by applying idiomatic approaches to real-world software design»?

Write safer, more maintainable Rust code by identifying anti-patterns, applying idiomatic design patterns tailored to ownership, borrowing, and the type system, and learning when to adapt or avoid traditional solutions.Free with your book:

Похожие материалы