Leaning into Rust
local graph
Chapter 13 — Leaning into Rust
Section titled “Chapter 13 — Leaning into Rust”Leaning into Rust
Section titled “Leaning into Rust”Throughout this book, we’ve journeyed through three distinct projects, each teaching the same fundamental lesson from a different perspective: the most effective Rust code comes from working with the language rather than against it. The Bad Calculator project showed us what happens when we fight Rust’s constraints. The Correct Calculator project demonstrated how traditional patterns transform when adapted thoughtfully to Rust’s ownership model. The Samsa microservice revealed patterns that leverage Rust’s unique features to create systems that are simultaneously safe, fast, and expressive.
What distinguishes this journey is not the specific techniques we learned in each project, but the mental transformation they represent. The Bad Calculator’s anti-patterns seemed like they were just mistakes for us to avoid, but we discovered that they were also symptoms of attempting to write Java, Python, or C++ code in Rust syntax. The adapted patterns in the Correct Calculator demonstrated how ownership and the type system affect basic software architecture, going beyond simple translations of Gang of Four designs. The Samsa microservice’s Rust-specific patterns were not just clever tricks. They presented a novel way of approaching type safety, error handling, and resource management.
This chapter isn’t about introducing new patterns or techniques. We’ve covered those thoroughly in the preceding chapters. Instead, this is a moment to step back and reflect on what we’ve learned. Each project taught us something about effective patterns, the tools Rust provides, and how to think differently about software design. By examining these lessons across all three projects, we can see the common threads that define truly Rust-native development.
The transformation from writing Rust code to thinking in Rust is complete when you stop translating from other languages and start designing from first principles with ownership, types, and zero-cost abstractions as your foundation. The three projects we’ve built together chart this transformation. Let’s reflect on what they taught us.
In this chapter, we’re going to cover the following main topics:
- Recognizing and applying patterns that feel natural in Rust by reviewing what we learned from the Bad Calculator, Correct Calculator, and Samsa projects
- Understanding the tools, features, and protections Rust provides as active development aids, not obstacles to overcome
- Developing a Rust-native mindset that transforms how you approach software design problems at every level
Technical requirements
Section titled “Technical requirements”To complete the exercises in this book, you’ll need a Rust toolchain installed. The examples in this book were developed using stable Rust, version 1.78.0, which is the minimum version for working on the exercises. Using rustup to install a recent toolchain version is recommended. It can be found here: https://rustup.rs/. This includes the instructions on installing and using it.
Code examples are available in the GitHub repository: https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust. Reference the ch1/ through ch13/ folders for complete, runnable code examples and the complete project evolution.
Use patterns natural to the language
Section titled “Use patterns natural to the language”The first and most fundamental lesson from our three projects is recognizing which patterns align with Rust’s design philosophy and which create unnecessary friction. Every time we found ourselves fighting the compiler, adding complex workarounds, or writing code that felt unnatural, we were swimming against the current. Every time the code felt clean, simple, and obvious, we were working with Rust’s grain.
What the Bad Calculator taught us
Section titled “What the Bad Calculator taught us”The Bad Calculator project in Chapters 1 through 4 was deliberately constructed to show anti-patterns – approaches that fight against Rust rather than work with it. Each anti-pattern revealed a different way in which thinking from other languages breaks down in Rust.
When we littered code with Rc<RefCell
When we cloned data excessively to satisfy the borrow checker, we were treating Rust’s ownership system as an obstacle to work around rather than a design constraint to respect. The performance cost of cloning was just a symptom. The real problem was that excessive cloning indicated we hadn’t thought through ownership relationships in our design.
When we fought the borrow checker with increasingly complex lifetime annotations and reference juggling, we were missing the message the compiler was sending: our design had structural problems. The borrow checker wasn’t being difficult. It was pointing out that we were trying to maintain invariants manually when they should be encoded in our types.
The Bad Calculator’s most important lesson was recognizing the feeling of fighting against Rust. When you’re constantly fighting the compiler, the issue is usually not with the compiler itself but with the approach. This recognition represents the first step toward Rust-native thinking.
What the Correct Calculator taught us
Section titled “What the Correct Calculator taught us”The Correct Calculator project in Chapters 5 through 8 showed how traditional Gang of Four patterns adapt, not port, to Rust. Each pattern required rethinking in terms of ownership, traits, and Rust’s type system. The patterns that worked best were those that aligned with Rust’s strengths rather than trying to replicate object-oriented inheritance hierarchies.
Rust’s Builder pattern, which combines the standard Builder pattern with a fluent interface, evolved into a means of enforcing proper construction via the type system. Each builder method consumed self, which allowed us to use ownership to prevent reuse in intermediate states. By making the final build() method fallible, we centralized validation. The pattern felt natural because it worked with ownership rather than against it.
The Strategy pattern shifted from runtime polymorphism through interfaces to a choice between static dispatch with generics and dynamic dispatch with trait objects. We learned how to choose based on whether the strategy needed to be determined at compile time or runtime. Both approaches felt natural because traits elegantly model behavior in Rust.
The State pattern found its ideal expression in the TypeState pattern, where different states become different types. This wasn’t possible in languages such as Java or C++ without tremendous boilerplate, but in Rust, zero-cost abstractions meant we could encode state machines in types that compiled away completely. Invalid state transitions became compile errors rather than runtime panics.
The Correct Calculator taught us that traditional patterns are valuable in Rust, but they must be translated. The translation is not only syntactic but also conceptual. We do not ask, “How can I write this Java pattern in Rust?” Instead, we ask, “What problem does this pattern solve, and how do Rust’s ownership and type system tackle it?”
What Samsa taught us
Section titled “What Samsa taught us”The Samsa microservice in Chapters 9 through 12 introduced patterns that leverage features specific to Rust, patterns that would be impossible, impractical, or inefficient in other languages. These patterns showed what becomes possible when you design from first principles with Rust’s unique features.
The NewType pattern wrapped primitive types to add semantic meaning and prevent misuse. While other languages have similar concepts, Rust’s zero-cost abstraction meant these wrappers added no runtime overhead while providing compile-time safety. We could create types such as TopicId, ConsumerId, and MessageId that prevented accidentally mixing up identifiers while compiling to the same efficient representation as raw primitive values.
The parse, don’t validate pattern used the type system to maintain invariants throughout the program. Instead of validating data repeatedly, we validated once at system boundaries and encoded the validation in types. A TopicId couldn’t exist if validation failed, and functions accepting TopicId knew they were working with valid data without checking.
We first encountered the TypeState pattern in Samsa while trying to model state transitions in the consumer lifecycle, as well as in the message processing stages of the system. Operations that only made sense in certain states became impossible to call in other states. The compiler ensured that we couldn’t poll a consumer that wasn’t in the Subscribed state. The poll() method simply didn’t exist for Connected or Paused consumers.
Functional patterns such as iterator chains, Result composition with the ? operator, and Option combinators felt completely natural in Samsa. These functional features were integral to the Rust code flow, not just add-ons. The iterator system streamlined complex transformation pipelines into efficient loops that eliminated intermediate allocations, and it also integrated neatly with Result and Option to produce clean, fluent code.
Samsa taught us that Rust enables patterns impossible in other systems languages. The combination of zero-cost abstractions, a powerful type system, and ownership tracking creates possibilities unavailable in C or C++ while maintaining the performance characteristics those languages provide.
Recognizing natural patterns
Section titled “Recognizing natural patterns”Across all three projects, a clear pattern emerged: code that feels natural in Rust shares certain characteristics. It uses ownership to clarify responsibilities rather than fighting ownership with reference counting and interior mutability. It encodes invariants in types rather than enforcing them with runtime checks. It leverages traits for behavior abstraction rather than trying to recreate inheritance hierarchies. It uses the compiler as a development aid rather than an obstacle to overcome.
When you find yourself writing code that feels awkward, verbose, or fragile, stop and ask whether you’re working with Rust or against it. The Bad Calculator showed us what against looks like. The Correct Calculator and Samsa showed us what with looks like. The difference is a fundamental change in approach rather than just the quality of the code.
Allow the language to help you
Section titled “Allow the language to help you”The second major lesson from our journey is recognizing that Rust provides powerful tools, features, and protections that actively improve code quality when we learn to work with them rather than around them. What initially appears as strict enforcement reveals itself as helpful guidance toward better designs.
The borrow checker as design consultant
Section titled “The borrow checker as design consultant”Early in our journey with the Bad Calculator, the borrow checker felt like an adversary. Every attempt to share mutable state triggered errors. Every complex borrowing scenario required careful thinking about lifetimes. It seemed the compiler was making simple things hard.
But as we progressed through the Correct Calculator and Samsa, a different picture emerged. The borrow checker wasn’t making things hard. It was pointing out where our designs had problems. When we couldn’t borrow something mutably because we held an immutable reference elsewhere, the compiler was telling us that our function had unclear ownership responsibilities. When lifetime errors appeared, the compiler was revealing that our data flow wasn’t as clear as we thought.
Consider the complex expressions in the Bad Calculator. An early design tried to view and modify the expression history from multiple places through the same reference. The borrow checker rejected this, not because it was being difficult, but because the design had a real problem: we were trying to mutate state we were also reading. The solution wasn’t to fight with lifetimes or wrap everything in RefCell, but to redesign so ownership was clear. The final design processed one message at a time with clear ownership of expression history, and the borrow checker approved immediately.
The transformation in thinking comes when you start to trust the borrow checker. When it complains, instead of looking for workarounds, look for design improvements. More often than not, the code that satisfies the borrow checker is also clearer, more maintainable, and more correct than the code you originally tried to write.
The type system as design tool
Section titled “The type system as design tool”The type system in Rust goes far beyond catching null pointer errors or type mismatches. Our three projects showed how types become a primary design tool for encoding domain knowledge and business rules.
In the Bad Calculator, we used primitive types everywhere: i32 for values, String for operations, and Boolean flags for state. This approach works in dynamic languages, but in Rust, it missed the opportunity to use types as documentation and enforcement. Values could be used in wrong contexts, operations could be invalid, and state invariants existed only in comments.
The Correct Calculator began using types more intentionally. Enums represented operations rather than strings. Structs grouped related data. Traits were used to define behavior contracts. But we still treated types primarily as organization tools rather than design tools.
Samsa took types to their logical conclusion. The TypeState pattern made entire classes of bugs impossible by encoding state machines as types. Consumer states (Disconnected, Connected, Subscribed, and Paused) became different types, and transitions became functions that consumed one type and returned another. You literally couldn’t call poll() on an unsubscribed consumer because that method didn’t exist for that type.
The parse, don’t validate pattern used newtypes to encode validation in the type system. A ValidatedTopic could only exist if validation succeeded. Functions accepting ValidatedTopic didn’t need to validate. The type system guaranteed validity. This moved error handling to system boundaries and eliminated redundant checks throughout the code base.
The lesson is to design with types first. Don’t think “I need to store some data; I’ll use these types.” Instead, think “What invariants must hold, what states are valid, and what transitions are legal?” Then, create types that make invalid states unrepresentable. The type system becomes documentation that the compiler enforces.
Error handling as first-class design
Section titled “Error handling as first-class design”Rust’s Result and Option types transformed error handling from an afterthought into a fundamental part of program design across all our projects. The progression from ignoring errors in the Bad Calculator to handling them properly in the Correct Calculator to making them central to design in Samsa showed the power of explicit error handling.
The Bad Calculator sometimes returned Option values and ignored the None case, sometimes used unwrap() to panic on errors, and generally treated error handling as something to add later. This approach is effective in languages that have exceptions, allowing for error handling far from the point of occurrence, but in Rust, it results in unreliable code. The Correct Calculator used Result types throughout and handled errors properly with the ? operator. This ensured that errors were always addressed and made error paths explicit in function signatures. But we still thought of error handling as something we had to do to satisfy the type system.
Samsa revealed error handling as a design tool. The configuration loading system used Result composition to try multiple configuration sources with automatic fallback. Message processing used Result to separate successful processing from failures, enabling batch processing that collected both results and errors. The ? operator made error propagation feel natural rather than burdensome.
Result and Option aren’t just error-handling mechanisms. These types are ways to make partial functions total, to make failure explicit, and to compose operations that might fail. The monadic operations (map, and_then, and or else) create powerful error-handling patterns that would be verbose or impossible in languages with exceptions.
Ownership as automatic resource management
Section titled “Ownership as automatic resource management”Ownership is a complete resource management system, not just memory protection. The development of our three projects demonstrated how ownership gets rid of whole categories of resource management issues.
The Bad Calculator demonstrated what happens when you don’t trust ownership. Liberal use of Rc led to unclear ownership semantics and confusion about when resources would actually be cleaned up.
The Correct Calculator used ownership properly for memory management, but we hadn’t yet explored how ownership applies to other resources, such as file handles, network connections, or locks. That broader application would come with Samsa. We wrote careful Drop implementations and tried to ensure that cleanup happened, but it required discipline.
Samsa embraced ownership as comprehensive resource management. Connection pools used guards that returned connections to the pool when dropped. File handles closed automatically when they went out of scope. Transaction guards rolled back transactions if not explicitly committed. The ownership system ensured resources were cleaned up correctly, even in error paths, without requiring manual try/finally blocks.
The resource acquisition is initialization (RAII) pattern from C++ finds its perfect expression in Rust. Where C++ RAII requires programmer discipline to avoid use-after-free bugs, Rust’s ownership system enforces correct usage at compile time. You literally cannot use a resource after it’s been dropped because the compiler prevents it.
Tooling as a quality force multiplier
Section titled “Tooling as a quality force multiplier”Throughout this book, we’ve focused on patterns and design practices, which are the what and the why of Rust code. But patterns don’t exist in isolation. The Rust ecosystem provides tools that reinforce good design by catching issues early, enforcing consistency, and providing rapid feedback. While we haven’t discussed these tools explicitly in earlier chapters, they’re natural companions to the patterns we’ve explored. Understanding how to leverage them completes your development workflow.
Rust’s tooling ecosystem actively improves code quality when integrated into the development process. Our projects benefit increasingly from tooling as we learn to use it effectively.
Cargo provides far more than dependency management. cargo check gives fast feedback on compilation issues. cargo test makes testing first-class with no external framework needed. cargo doc generates documentation from code comments and makes it easy to document everything. cargo bench provides built-in benchmarking for performance-critical code.
clippy goes beyond basic linting to suggest idiomatic Rust patterns. It catches potential bugs, suggests performance improvements, and teaches us better ways to express ideas in Rust. Its suggestions can shape our coding style toward increasingly idiomatic Rust.
rustfmt eliminates formatting debates and reduces cognitive load. Consistent formatting means we can focus on what code does rather than how it looks. These features become particularly valuable as the code base grows.
The Rust Language Server and rust-analyzer provide IDE integration that makes the compiler’s knowledge available while coding. Type hints, inline error messages, and automatic refactoring support make development faster and more reliable.
The lesson is to integrate these tools into your workflow from the start. Don’t wait until the code is “done” to run clippy. Don’t think of tests as something to add later. Let the tools guide your development continuously, and they become force multipliers for quality.
Compiler-driven development
Section titled “Compiler-driven development”One of Rust’s most powerful features is how the compiler can guide development. This became increasingly apparent as we progressed through our projects.
The approach is simple: write types that express your intent, then implement the logic you want. When the compiler complains that a function doesn’t exist, implement it. When it complains about missing trait implementations, add them. When it complains about borrowing issues, redesign until the ownership is clear. This method works because Rust’s compiler errors are precise and helpful. They tell you exactly what’s wrong and often suggest fixes. The errors aren’t obstacles but to-do items guiding you toward a complete, correct implementation.
In Samsa, we used this approach extensively when developing the code. We’d define the Broker type with the fields it needed, then start writing the public API we wanted. The compiler would tell us what private helper methods to implement. When we added new features, we’d update types first, and the compiler would tell us everywhere we needed to update logic. This made large refactorings safe and straightforward.
The real shift is learning to see compiler errors as helpful rather than frustrating. When you trust that satisfying the compiler leads to correct code, development becomes a conversation with the compiler rather than a fight against it.
Think in Rust
Section titled “Think in Rust”The final and most profound lesson from our journey is that truly effective Rust development requires a transformation in how you approach software design itself. Internalizing Rust’s philosophy and allowing it to shape your approach to problems is more important than just learning syntax and patterns.
The mental shift: three projects, one lesson
Section titled “The mental shift: three projects, one lesson”The progression from Bad Calculator through Correct Calculator to Samsa wasn’t just about learning more advanced techniques. It was about a fundamental shift in thinking. Each project represented a stage in that transformation.
The Bad Calculator represented thinking from other languages. We approached problems with solutions from Java, Python, or C++ and tried to express them in Rust syntax. The result was code that compiled (sometimes) but fought against Rust at every turn. This is where most developers start with Rust, and it’s frustrating because you’re trying to use Rust as a worse version of a language you already know.
The Correct Calculator represented translation thinking. We understood that Rust required different approaches, and we adapted traditional patterns thoughtfully. We learned to use traits instead of interfaces, ownership instead of garbage collection, and enums instead of inheritance hierarchies. This is a crucial stage, but it’s still essentially translating from other paradigms rather than thinking natively in Rust.
Samsa represented Rust-native thinking. We based our design on first principles, using ownership, types, and zero-cost abstractions as foundational elements instead of viewing them as constraints. We did not ask, “How do I do X from language Y in Rust?” We asked,
“What is the Rust solution to this problem?” The result was code that felt natural, elegant, and powerful in ways that wouldn’t be possible in other languages.
The transformation is complete when you stop translating and start thinking directly in Rust concepts. You don’t think, “I need shared mutable state, so I’ll use Rc<RefCell
Ownership as a design philosophy
Section titled “Ownership as a design philosophy”The Bad Calculator showed what happens when you try to avoid thinking about ownership. Everything becomes shared and mutable through Rc<RefCell
The Correct Calculator started thinking about ownership deliberately. Builder patterns consumed self to prevent reuse. Factory patterns returned owned values with a clear ownership transfer. State patterns moved data between states rather than mutating it in place. These weren’t workarounds; they were designs that made ownership relationships explicit.
Samsa was designed with ownership first. The broker owned topics and subscriptions. Connections owned their state. Messages were owned by exactly one component at a time and moved through the system with clear ownership transfers. When we needed shared access to metrics, we used Arc consciously, understanding that we were sharing immutable data or data protected by synchronization.
Thinking in ownership means designing APIs around ownership relationships. A function that takes ownership consumes the value; the caller can’t use it afterward. A function that borrows immutably allows sharing. A function that borrows mutably requires exclusive access. These technical details communicate your design intent and allow the compiler to enforce it.
Zero-cost abstractions as a mindset
Section titled “Zero-cost abstractions as a mindset”The phrase zero-cost abstraction means you can write high-level, expressive code without paying runtime performance costs. But thinking in zero-cost abstractions means actively choosing abstractions that compile away rather than those that add overhead.
We were concerned about performance, so the Bad Calculator avoided abstractions. We used primitive types, imperative loops, and duplicated logic instead of relying on abstractions. However, this did not improve performance and instead resulted in bugs and more difficult-to-maintain code. The Correct Calculator used abstractions but worried about their cost. We used iterators, but wondered whether they were as fast as loops. We used traits but worried about dynamic dispatch overhead. We struggled to balance our desire for expressive code with our fear of performance penalties.
Samsa embraced zero-cost abstractions fully. Iterator chains replaced imperative loops, compiling to the same efficient code. The TypeState pattern encoded state machines in types that disappeared at compile time. Newtype wrappers added semantic meaning with no runtime representation. We wrote high-level, expressive code with confidence that it would compile to efficient machine code.
Rust’s zero-cost abstractions are not just a feature but also a design philosophy. You can write code that’s both expressive and performant. You don’t have to choose between clean code or fast code. The iterator chain is both more readable and often faster than the equivalent imperative loop because the compiler can optimize the high-level intent.
Thinking in zero-cost abstractions means preferring iterator chains over loops, using newtypes for semantic clarity, encoding state in types through the TypeState pattern, and generally choosing expressive abstractions with confidence that they’ll compile away.
Safety without paranoia
Section titled “Safety without paranoia”Rust’s safety guarantees fundamentally change how you think about defensive programming. In languages such as C or C++, you add checks everywhere because anything might be null, any pointer might be invalid, and any data might be corrupted. In languages such as Python or JavaScript, you add type checks because the type system won’t help you.
You can write code in Rust with less defensive paranoia because you can trust the type system to enforce safety. This is encoding safety in types and relying on the compiler to enforce it, not writing unsafe code.
The Bad Calculator demonstrated paranoid programming poorly adapted to Rust. We added runtime checks for conditions that the type system could prevent, used unwrap() in places where failures were possible, and generally didn’t trust the safety guarantees Rust provided.
The Correct Calculator started using types for safety. Option types eliminated null checks. Result types made errors explicit. Enums with data ensured that we handled all cases. We still added some runtime checks, but increasingly, we encoded invariants in types.
Samsa took this to its logical conclusion. The TypeState pattern made entire classes of invalid operations impossible to express. The parse, don’t validate pattern moved validation to system boundaries and encoded it in types. Functions accepting validated types didn’t need to check them, because the type system guaranteed validity. We wrote less defensive code because the compiler defended us. Consider the difference.
Here’s the defensive approach, with runtime checks everywhere:
fn send_message(topic_id: u64, message: &[u8]) -> Result<(), String> { if topic_id == 0 { return Err("invalid topic".into()); } if message.is_empty() { return Err("empty message".into()); } // ... more checks ...}The type-safe approach ensures that it is impossible to call the function with invalid data:
fn send_message(topic: TopicId, message: ValidatedMessage) -> Result<MessageId, BrokerError> { // No checks needed - types guarantee validity}The type-safe method is not only cleaner but also more effective. It uses types to uphold the guarantee that the function call will always be valid and shifts validation to the precise location where erroneous data enters the system. Because the check is encoded in the type system, you cannot inadvertently forget it.
Asking “How can I make this impossible to use incorrectly?” as opposed to “How do I check for all possible errors?” is a way to think safely and without paranoia. Instead of writing defensive checks everywhere, it entails encoding invariants using types.
Composition over inheritance, naturally
Section titled “Composition over inheritance, naturally”The lack of inheritance in Rust is not a barrier to overcome; rather, it serves as a guide for improved design patterns. The development of our projects demonstrated how composition, rather than inheritance, produces systems that are more adaptable and maintainable.
The Bad Calculator tried to work around the lack of inheritance by using trait objects everywhere, creating complex hierarchies of traits, and generally trying to recreate the object-oriented patterns we knew. Such attempts led to unnecessary complexity and missed Rust’s actual strengths.
The Correct Calculator learned to use composition with traits effectively. The Strategy pattern composed behavior through trait objects when runtime polymorphism was needed, or through generics when compile-time polymorphism sufficed. The State pattern composed states rather than inheriting from them.
Samsa demonstrated composition thinking throughout. The BrokerService composed a core Broker with an optional ConnectionPool and configuration, with each as a separate component. Components could be tested independently, replaced easily, and composed in different ways for different use cases. This flexibility would be difficult with inheritance hierarchies.
Composition thinking means asking, “What does this component need?” and providing those capabilities through composed dependencies rather than inherited behavior. It means preferring has-a relationships over is-a relationships. It means using traits to abstract behavior without coupling implementation to type hierarchies.
Explicitness as a core value
Section titled “Explicitness as a core value”Rust culture values explicitness over cleverness, and this shapes everything from API design to error handling. The progression through our projects showed how explicitness leads to more maintainable systems.
The Bad Calculator tried to be clever with implicit conversions, operator overloading, and magical behavior. We thought we were making the API convenient, but we were actually making it unpredictable and difficult to debug.
The Correct Calculator used explicit conversions with From and Into traits, made error handling explicit with Result types, and designed APIs that clearly communicated their behavior. The code was more verbose but much easier to understand.
Samsa embraced explicitness as a virtue. Different kinds of sends (send(), send_text(), and send_keyed()) were separate methods with clear names rather than one method with mode flags. State transitions in the TypeState consumer were explicit type transformations. Error types such as SamsaError::topic() and SamsaError::broker() were specific and informative, telling you exactly what went wrong.
Explicit APIs are easier to learn, easier to use correctly, and easier to debug when something goes wrong. The clarity more than compensates for the slight verbosity.
From writing Rust to thinking in Rust
Section titled “From writing Rust to thinking in Rust”The transformation from writing Rust code to thinking in Rust is complete when these principles become natural. You design with ownership first, without thinking about it consciously. You encode invariants in types automatically. You trust the compiler’s guidance. You write explicit, composable code that leverages zero-cost abstractions.
This transformation is visible in the progression from Bad Calculator to Samsa. Each project represented a stage in learning to think in Rust. The Bad Calculator was written in Rust syntax with non-Rust thinking. Samsa was written with Rust thinking from the ground up.
The journey doesn’t end. Rust continues to evolve, new patterns emerge, and different problem domains require different approaches. But once you’ve internalized Rust’s philosophy, you have the foundation to tackle any challenge in a Rust-native way.
Summary
Section titled “Summary”Our journey through three projects – the Bad Calculator, the Correct Calculator, and the Samsa microservice – taught us far more than specific techniques or patterns. The projects showed us a transformation in thinking about software design itself.
The three principles we’ve explored – using patterns natural to the language, allowing the language to help you, and thinking in Rust – aren’t separate lessons. They’re interconnected aspects of a unified approach to development. Natural patterns feel natural because they work with ownership and types. The language helps you when you trust its guidance rather than fighting it. Thinking in Rust means internalizing these principles until they become automatic. Each project reinforced these principles at different scales and in different contexts.
The transformation this represents goes beyond Rust itself. It can improve your software design thinking even outside Rust. Rust’s constraints force you to think more carefully about design, and that careful thinking creates better software.
As you apply these ideas in your own work, remember that mastery comes from internalizing principles rather than memorizing techniques. When you truly think in Rust, you’ll find yourself naturally choosing approaches that are safe, fast, and maintainable. You’ll catch design problems early because the language guides you toward better solutions. You’ll write code that is both high-level and performant because you understand how Rust’s abstractions work.
The Rust community’s culture of sharing discoveries and helping each other learn means that the best ways to apply established patterns continue to evolve. As developers tackle new challenges, they’ll discover new ways to combine Rust’s unique qualities with established programming patterns and share their solutions with the community.
Take these principles, experiment with them, and make them your own. When you discover new ways to apply patterns or better approaches to solving problems, share them with the community. The future of Rust depends not just on the language itself but also on the collective wisdom of developers who choose to lean into it rather than fight against it. The transformation from thinking about Rust as a challenging language to thinking of it as an enabler of great software is complete when you realize that Rust hasn’t just changed how you write code. It has changed how you think about what good code can be. The journey from Bad Calculator to Samsa represents that transformation, and now you’re equipped to continue it in your own work.
Get this book’s PDF version and more
Section titled “Get this book’s PDF version and more”Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
UNLOCK NOW
Note: Keep your invoice handy. Purchases made directly from Packt don’t require an invoice.
[hallucinated OCR output quarantined; see source PDF page for authoritative content]