Why Is Rust Different?
local graph
Chapter 1 — Why Is Rust Different?
Section titled “Chapter 1 — Why Is Rust Different?”1 Why Is Rust Different?
Section titled “1 Why Is Rust Different?”In this chapter, we’ll learn why designing, architecting, and coding in Rust require different techniques, different design patterns, and different ways of thinking than you may be used to from previous experience. Experienced developers have a toolbox of patterns and strategies that they’ve learned and developed over time that serve them very effectively. Why doesn’t that toolbox work the same way for Rust? We’ll talk about that here.
First, we’ll discuss why familiar patterns don’t work and why new ones are needed. Then, we’ll discuss why even very experienced programmers can face difficulties beyond just learning the language and sometimes find Rust infuriating. We’ll talk about the process of becoming fluent in Rust, as well as the common pitfalls and milestones in the journey. We’ll round out this chapter by discussing the importance of thinking from a Rust perspective when working with the language.
We’ll also introduce our first project, where we’ll build a calculator program using familiar, tried, and true patterns and discover the issues that we encounter when we rely on some of these practices.
Above all, in this chapter, and the ones that follow, we’ll focus on what works, what doesn’t, and how to use the language effectively.
In this chapter, we’re going to cover the following main topics:
- Why do I need new patterns?
- Hitting the wall
- The Rust learning curve
- Learning to think in Rust
- Let’s build a calculator, badly!
Note: Your purchase includes a DRM-free PDF copy of this book, a 7-day trial to the Packt+ library (no credit card required), and additional exclusive extras. See the Free benefits with your book section in the Preface to unlock them instantly and maximize your learning.
Why do I need new patterns?
Section titled “Why do I need new patterns?”In this section, we’ll discuss the need for new design patterns for Rust. We’ll discuss how patterns reflect the language that they were built for, and how Rust can appear similar to familiar languages but is more different than it seems, requiring a new set of tools to code effectively.
Working with the familiar
Section titled “Working with the familiar”As developers, we’ve put considerable time and effort, often years or even decades, into learning our craft. We each try to build knowledge of the most effective practices to create robust, clean, and elegant code, either through our own experience or through learning from the experiences of other people. We rely on that knowledge to steer us away from danger and toward solid solutions.
Design patterns have become a standard in developing software because they’re a clear, expressive, and concise way of sharing knowledge that can direct us to excellent results. Names such as the Visitor pattern and the Observer pattern are commonplace, and builders and factories are known to almost everyone. By studying and using design patterns, we can benefit from the experience of thoughtful people who have faced similar challenges. They pre-load our toolbox with useful tools for situations that we may not have ever seen, and lead us to successful projects.
One of the things that has made the traditional design patterns so successful and so widely used is their extremely broad applicability. The same commonly known design patterns work across a variety of programming languages, domains, frameworks, and applications. They keep being effective in a Rust web service, a TypeScript frontend, or a C++ game engine. In so many situations, your familiar tools don’t fail you.
Experience can be misleading
Section titled “Experience can be misleading”As a developer learns Rust, they first learn the basics of the language. Once they have those in hand, it’s natural for them to reach for the same patterns and principles that have always worked for them. This makes sense because once you get used to some of Rust’s unique qualities, there’s much that feels familiar: structs seem like objects, traits seem like interfaces, and methods even have the same name. Associated functions aren’t exactly constructors or static methods, but they feel very similar. Once you’ve learned the basics of the language, you feel at home and ready to open your toolbox and get to work.
This sense of familiarity can be deceptive. While familiar design patterns can seem to work as you would expect at first, Rust is more different than it appears, and it sometimes needs different approaches and techniques to produce the high-quality results that you’re trying to achieve. Rust often requires new patterns for familiar solutions, and even in situations where familiar patterns work, they may require a twist so that they can be adapted to Rust’s unique model.
The reason that the familiar design patterns work so perfectly in so many situations is that popular programming languages share many common traits and design choices. You could say that languages as diverse as Python and C++ share common patterns in their design, and because of this, we can use common design patterns across so many languages, frameworks, and applications.
Like virtually all modern programming languages, Rust borrows from and is inspired by earlier languages. It takes lessons, and sometimes core elements, from what came before, and it reuses and remixes them in unique ways. Rust looks familiar in many ways because there is much that’s familiar.
But Rust is also different. Sometimes, the differences are obvious, such as new syntax or different rules that must be followed. Some are more subtle, such as Rust’s move semantics or understanding the difference between generics and associated types. But some of the differences are at the core of the way the language is supposed to work. These differences can be invisible, but they’re exactly the differences that cause so much difficulty for developers as they begin to write more and more advanced code.
To write code in Rust, we need a new toolbox. Some of the tools will be familiar. Some will be a bit different, but recognizable. Others will be new.
In the next section, we’ll work through an example. We’ll see how making what feels like the simplest design decision can lead to infuriating errors when we don’t take Rust’s core principles into account.
Example – parsing messages in place
Section titled “Example – parsing messages in place”Let’s suppose that we need to process a lot of incoming messages and parse their content. The messages are in text format, and they contain a lot of data. Within each message is a header and then different blocks or sections that are their own sub-messages of different kinds. The different kinds of sub-messages also each have a header, and then a field structure unique to that message type.
Let’s suppose that it’s important to keep the original unparsed form of the message to be used for some purpose and that all messages need to be kept in memory.
Fortunately for us, our task is simple: we just need a way to find specific blocks within a message and return an object that can be used to read the bytes in the block, presumably for more parsing, but we don’t care what they’ll do with the characters. We just need to provide an object that can read the bytes of one specific block in one specific message.
With so many messages and with so much data that all needs to be kept in memory, it isn’t practical to copy the data, so we want to reference the bytes in place in the message.
Regarding our requirements, we need to write a function that does the following:
- Takes a reference to a message in memory and a block identifier (call it an integer).
- Keeps that message intact.
- Finds the specific block for that identifier within the message.
- Returns an object that can be used to read the bytes of that block (but doesn’t copy it).
I have excellent news! Someone has already written a Rust function that will find the offset and length of the block for us if we provide the block identifier.
More excellent news! There’s a vast collection of really helpful Rust crates that we could potentially use to help us at https://crates.io. There could be something there that we could add to our Cargo.toml file.
But we don’t even have to do that! The Rust standard library contains std::io, which provides useful traits and structs that will do most of the work for us. We can use the Read trait to represent our byte reader object, and the Cursor struct to do the actual work of reading the bytes.
This will be easy! Here’s an implementation of the block reader that meets all the requirements outlined previously:
use std::io::{Cursor, Read};
fn find_block(_message: &[u8], _block_id: u64) -> (usize, usize) { todo!()}
struct BlockReader<'a> { message: Vec<u8>, block_reader: Cursor<&'a [u8]>}
impl Read for BlockReader<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { self.block_reader.read(buf) }}
fn new_block_reader(message: Vec<u8>, block_id: u64) -> BlockReader<'static> { let (pos, count) = find_block(&message, block_id); let slice = &message[pos..(pos+count)]; BlockReader { message, block_reader: Cursor::new(slice) }}Here’s what it does:
- It defines a placeholder version of our function
find_block, which accepts a message and returns a tuple of the position and byte count of the block (requirement 3). - It defines the
BlockReaderstruct, which keeps our original message (requirement 2), and aCursorstruct that can act as a proxy object to read the bytes (for implementing requirement 4). - It implements the
Readtrait forBlockReaderby just forwarding the read to theCursorstruct (requirement 4). - Finishing up, it implements the function described in requirement 1 that creates and returns our
BlockReaderstruct. - Within this function,
find_blockis used to determine the position and length of the block, and a slice is taken from the message (without copying, satisfying requirement 4). - A
Cursorobject is created from that slice. - Finally,
BlockReaderis constructed and returned (all requirements done).
Perfect! Now, we just need to build it:
$ cargo buildCompiling block_reader v0.1.0error[E0515]: cannot return value referencing function parameter `message` --> src/block_finder.rs:21:5 |20 | let slice = &message[pos..(pos+count)]; | ------- `message` is borrowed here21 | / BlockReader {22 | | message,23 | | block_reader: Cursor::new(slice)24 | | } | |___^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `message` because it is borrowed --> src/block_finder.rs:22:9 |18 | fn new_block_reader(message: Vec<u8>, block_id: u64) -> BlockReader<'static> { | ------- binding `message` declared here19 | let (pos, count) = find_block(&message, block_id);20 | let slice = &message[pos..(pos+count)]; | ------- borrow of `message` occurs here21 | / BlockReader {22 | | message, | | ^^^^^^^ move out of `message` occurs here23 | | block_reader: Cursor::new(slice)24 | | } | |_____- returning this value requires that `message` is borrowed for `'static`It seems that the compiler didn’t like that. We were depending on being able to keep a reference to the block from inside the message, but we didn’t remember that creating BlockReader means taking ownership of the message, which invalidates the reference.
We could spend hours trying to find a trick that would work (there actually is one), but what really happened here?
Here, we tried to use traditional object-oriented memory patterns that make sense in a language such as Rust but don’t for Rust. By object-oriented memory patterns, we mean the common practice of creating objects that can freely reference each other, often creating complex webs of relationships, without thinking about lifetimes or data races. The borrow checker sees us doing something dangerous and puts a stop to it.
What should we do?
We need to rethink what we’re doing to work with Rust, and not try to trick the borrow checker. We’ll revisit this example in the next chapter and find a more natural solution for Rust.
At this point, we understand why new patterns are needed for Rust. With that in mind, we can explore why so many developers start out learning Rust happily but run into difficulties when they move to more advanced projects.
Hitting the wall
Section titled “Hitting the wall”In this section, we’ll discuss the common problem of developers suddenly running into difficulties when they begin to work on more advanced projects after initial success with Rust. This is a crucial topic because it illustrates why applying design patterns that were effective in the developer’s previous experience can be a barrier to progress in learning Rust. We’ll begin by explaining this phenomenon and describing its effects. Then, we’ll discuss why it happens and what to do about it.
A sudden stop
Section titled “A sudden stop”There’s something that happens very often to developers who are in the process of learning Rust. It’s so common that it seems to be a topic constantly on Rust sites and forums. Despite being such a common experience, it doesn’t seem to have a name. So, let’s call it “hitting the wall.”
Many people start their Rust journey filled with enthusiasm. They know that the language is very popular and widely praised. They find a welcoming and supportive Rust community ready to help them. There’s plenty of high-quality beginner documentation, and there are many tutorials and guides.
Learning Rust is fun! It does have some aspects that are different, but when they’re first learning the language, developers often feel like they’re making progress almost every day and they can build projects of increasing complexity, leveraging more and more advanced features.
Eventually, they get to a place where they feel like they’ve finished the process and learned the language. Maybe they have worked through the Rust book, done the tutorials, asked questions, and built things. Now, they’re Rust programmers (Rustaceans!), and they’re ready to take on substantial projects.
That’s when, quite often, things suddenly get difficult.
The high-level design of the project doesn’t seem unusually difficult. They begin to code some modules that compile nicely and the unit tests seem to work. They build more, but then they hit the wall.
Something doesn’t compile, which is OK because that happens. However, they try to follow the recommendations from the error message, and that doesn’t compile either. They follow a chain back and fix many things as they work, but this causes even more things to not compile.
Taking a step back, they recognize that Rust doesn’t permit them to do what they’re trying to do, but the whole design requires them to do it. They’ve been trying to appease the compiler, but it won’t budge because it violates Rust’s rules.
They may try tricks to get around the issue. They may throw clone() everywhere, or they may wrap things in Rc<RefCell<T>>. They may try writing some unsafe code, or they may find a crate that will fix the issue they’re fighting with.
Sometimes, that works! But it leaves the code messy, inefficient, and quite possibly full of bugs. More often than not, that doesn’t help: the code doesn’t compile, it doesn’t work correctly, or it appears to work, only to have a different error appear later, after they’ve built more of the project.
I’ve heard people say that the Rust compiler hates them. I’ve heard them say that they hate Rust. I remember saying these things myself when I first hit the wall.
Learning why this happens
Section titled “Learning why this happens”The reason that so many developers have this experience can be summed up simply: for more advanced projects, applying architectural and design patterns from previous experience can lead to code that can’t be made to work properly in Rust. In learning Rust, it’s as necessary to learn to design for Rust as it is to learn the language itself.
What does this mean in practice?
-
Rust is not an object-oriented language: Because object orientation is so prevalent in modern programming languages, it becomes very natural to think in terms of objects and class hierarchies when designing architecture or building a system. This can seem to work in Rust because it does have some object-oriented-style features, but without inheritance and with severe limitations on polymorphism, trying to implement an object-based design usually leads to bad results. As we’ll discuss in the next chapter, trying to work around this issue with questionable tricks isn’t helpful.
-
The Rust borrow checker prohibits designs that are natural in most languages: Experienced developers who have begun using Rust are used to having the freedom to read, write, and share data with few restrictions. In learning Rust, they’ll understand that the language is different and that it restricts how data can be used and shared. However, if they continue to think about system architecture and design patterns in the ways that they’re used to, they’ll end up with designs that depend on being able to share and mutate data in ways that won’t work in Rust. On the level of structs and functions, the code will follow excellent practices, but flaws in the high-level design will mean that it will never be possible to make the whole system work. We’ll discuss this further in Chapter 4, Don’t Fight the Borrow Checker.
-
Rust uses functional programming paradigms to perform common tasks: Functional programming is baked into Rust. The Rust standard library, core Rust types, and even the basic design of the language are designed to leverage the power of functional programming. Because of this, designing a system that doesn’t take this into account will produce code that’s awkward, inefficient, confusing, and sometimes completely unworkable. On a basic level, system design in Rust needs to take this into account. Rust provides extremely helpful tools to assist in making concise, natural code flow with a functional design, but to use them, the system design needs to take this into account. We’ll discuss how to leverage this in Chapter 11, Patterns from Functional Programming.
-
Rust’s advanced type system is core to effectively designing for the language: Anyone who’s learned Rust is aware of its unique, expressive, and highly flexible type system. With it, there’s so much that’s possible to do that wouldn’t be possible in most languages. However, there are two sides to this. Because the type system can do so much, the language often makes it difficult or impossible to do things without leveraging the type system. When designing a system architecture, it’s necessary to think about types in a way that wouldn’t be required in most programming languages. Rust provides incredible tools but then expects the developer to use them. We’ll explore this more in Chapter 10, Patterns That Leverage the Type System.
-
Rust has unique features that are purpose-built to allow you to create correct, idiomatic code: As with the type system, Rust has a variety of unique features that make it possible to express things in the code that wouldn’t be possible in most programming languages. The “everything is an expression” model, the built-in utility types, the unique approach to resource acquisition is initialization (RAII), and the many ergonomic features of the language make it much easier to write clean, elegant code. But because these features are included in the language, Rust makes it difficult to work without them. As with the type system, these are often not just the preferred way, but also the only effective way to do things. We’ll discuss this more in Chapter 12, Patterns Emerging from Rust’s Core Features.
-
Rust has general architectural principles and patterns that are natural to the language: Rust lends itself naturally to certain design principles and architectural patterns. Just as it’s natural to design systems based on class hierarchies in Rust or C++, Rust has unique architectural patterns that feel inherent to the language itself. And just as it would be very unnatural to design a Rust program with just one class that has hundreds of static functions, designing a system in Rust will go badly without considering how architectural choices harmonize with the natural structure of idiomatic Rust programs. Basic principles such as paying attention to the flow of data, limiting the scope of mutability, structuring the code in terms of modules, and modularizing data to avoid issues with borrowing are all crucial to creating Rust architectures that work. Designing a Rust application without considering these things can lead to code that follows excellent coding practices but doesn’t fit together into a whole that works. Many endless battles with the compiler start with not taking these factors into account. We’ll discuss this further in Chapter 9, Architectural Patterns.
-
Trying to work around architectural issues with local fixes never works: When your Rust code won’t compile, sometimes it’s a simple error (or even a subtle one) that can be fixed by changing the code causing the error. Often, the compiler error message will say exactly how to fix the issue! But when fixing the error seems impossible, or it leads to a new error, and one after that, and one after that, it’s a sign that there’s a more serious structural issue. In these circumstances, it’s very tempting to throw everything at the error, including cloning, unsafe code, and many more ways to work around it. In these situations, it’s important to catch yourself and consider why, on a more basic level, you’re facing the error. Generally, you’ll discover the actual cause is a decision that was made much earlier, at the design level. We’ll discuss why “throwing everything at it” is a bad strategy in Chapter 3, Anti-Pattern: Using Clone and Rc Everywhere.
Hitting the wall is often a painful step in a developer’s Rust journey. It can be very discouraging and sometimes infuriating. However, it isn’t a necessary step. By learning how to apply architectural and design patterns specific to Rust, the wall can disappear and the road ahead can be clear.
In the next section, we’ll discuss that journey and the process of learning Rust, and we’ll discuss how design patterns can help at every step.
The Rust learning curve
Section titled “The Rust learning curve”In this section, we’ll discuss the unusual learning curve of Rust in comparison to most programming languages. It’s valuable to understand the common challenges that are faced by developers as they work to become proficient in the language because so many of these challenges come from not recognizing where new patterns are needed. We’ll start this section by discussing how learning Rust differs from learning most languages. Then, we’ll discuss common experiences in learning the language.
Learning Rust can feel very different
Section titled “Learning Rust can feel very different”Many things about Rust make it different from most languages. It brings together a variety of paradigms from earlier languages in a new way. The borrow checker was like nothing else in any language when it was introduced (though most of the foundations for it had been explored decades before). The async model is unique and radical. So much about Rust is like nothing else.
One more quality of Rust is, to my knowledge, found nowhere else: the Rust learning curve.
With almost all programming languages, the learning process has one constant, which is progress. Some languages are more difficult. Some are unusual or require new thinking. Some have so much to learn it takes years to absorb it all. But no matter how strange or how difficult the language is, day by day, each person learning the language sees progress over time. Anyone who keeps working at it will feel more knowledgeable, and more capable at every step.
However, for many people, the Rust experience can be quite different.
As we discussed in the previous section, developers learning Rust can often experience what feels like a profound setback just as they begin to feel truly comfortable using the language. That setback, that feeling of falling backward in the journey, can be so upsetting that some stop learning Rust completely.
But hitting the wall, while a substantial setback, is only one of the twists and turns in the Rust journey.
The uneven path
Section titled “The uneven path”The Rust learning process can be quite uneven. The language itself has many topics that can be confusing, including the borrow checker, lifetime annotations, traits, generics, associated types, asynchronous programming, unsafe Rust, and quite a few more. Fights with the compiler can come and go, and they can be unsettling when a developer thinks they’re beyond that.
What’s most troublesome is not having that sense of reliable progress. It can be incredibly wearing to feel a sense of pride and accomplishment, only to be back to nothing compiling the next day.
When I was in the process of learning Rust, I described it as the five stages of Rust grief:
-
Optimism: Initially, I felt excitement and enthusiasm about learning Rust. There was so much to discover and it was fun to explore. I quickly began to feel like I was starting to really know the language. The compiler error messages were even helpful and guided me to fix the errors and learn in the process.
-
Frustration: Suddenly, I was faced with compiler errors that were much more difficult to fix, or even to understand. I began to feel angry at the compiler, and even more angry at myself for seemingly moving backward. I would make progress for a time, but then I’d hit the next error and be back to feeling angry.
-
Doubt: The anger was bad, but when doubt began to set in, my journey with Rust hit its lowest ebb. I began to doubt myself and I began to doubt whether working with Rust even made sense. This was where I hit the wall.
-
Epiphany: In a moment of clarity, I saw things differently. I began to think about what I was doing differently. Not everything made sense, but I could see the path and I could understand how I needed to change my thinking. I began to appreciate Rust as I had at the beginning.
-
Mastery: With new ways of thinking, I found that my old enemy, the compiler, was now my friend and ally, and that Rust had become my favorite language.
Everyone’s journey with Rust is different, and not everyone will experience Rust grief as I did (I want this book to help you avoid it), but my experience isn’t unusual.
For me, the moment of clarity was this: I was writing a very intricate concurrent system, with many workers trying to share the same resources. I was familiar with concurrent programming, so I knew all of the dangers and how to avoid them. But my code wouldn’t compile. I fought with the compiler for hours, but nothing I tried made it compile.
Eventually, I took a step back and thought about what I was trying to do. What I realized was that I was trying to code a subtle data race bug, and the compiler wouldn’t let me do it. After the surprise wore off, I began to think about what I’d been doing throughout the project, and I saw that the tools that I was using, the patterns, the mental models, and the ways of thinking that I was applying to my Rust code didn’t fit. I knew how to write syntactically correct Rust, but I wasn’t thinking about what I was building in Rust terms.
That was my lightbulb moment.
Learning to think in Rust
Section titled “Learning to think in Rust”In this section, we’ll learn about the value of changing the way that we think about Rust code. Learning new design patterns can make a dramatic difference in a developer’s success with Rust, but also learning the reasons behind these new patterns can multiply that success. We’ll begin by discussing how our thinking is shaped by the programming languages that we’re comfortable with, and how our thinking then shapes our solutions when learning a new language. Then, we’ll discuss how creating a correct mental model by understanding these design patterns can take us beyond what the patterns themselves can do.
Thinking in code
Section titled “Thinking in code”The purpose of this book is to teach useful design patterns and effective coding practices so that you can write high-quality, robust, idiomatic Rust code. These practices and patterns can substantially improve the experience and results when working on Rust projects, but there’s something else to consider.
If you’re an experienced developer, then Rust most likely isn’t your first programming language, and you probably had considerable experience in one or more languages before you began learning Rust. Whether it’s Python, C#, TypeScript, or something more exotic, you’ll have become so comfortable using the language that it feels no different than speaking or writing your native human language.
You’re thinking in code.
But, as with human languages, you’re thinking in a specific kind of code – the language that you’re comfortable with. This understanding extends far beyond the syntax and features of the language and its standard library. You know how things work, what to do in what situations, and the flow of the language. You don’t have to think about it because you are thinking in it.
And you know something else: you know design patterns. But you don’t just know the official, named ones. You know hundreds of them, none of which have names, because you don’t think of them as design patterns – you just know what to do.
If you haven’t reached that place in your journey, you will.
Seen from this perspective, hitting the wall and the Rust learning curve make sense. They are steps on the way to thinking in Rust.
Finding understanding
Section titled “Finding understanding”Throughout this book, we’ll be learning new design patterns, discovering what works and what doesn’t, and thinking about structuring code so that it works optimally with Rust. We’ll explore how to make use of some familiar patterns and also some unique ones made possible by Rust’s unique qualities.
In addition, we’ll be discussing why things work, and why they don’t. We’ll not only talk about how familiar patterns can be used or changed to be more effective in Rust – we’ll also explore the reasons they harmonize with Rust and the reasons that changes may be necessary. When we explore architectural choices that provide a foundation for solid, elegant design, we’ll also explore what it is about Rust that makes these choices so effective. When we talk about unique patterns that are made possible by Rust’s features, we’ll also discuss how these features create new possibilities and talk about ways to leverage those features to create our own possibilities.
The goal of all of this is to help you understand where these patterns came from so that you can discover your own.
The goal is to help you to think in Rust.
Rust is a relatively young language. One thing that’s interesting that sometimes comes up in discussions of Rust design patterns is that some very widely known and used crates use flexible, elegant patterns that don’t have names. As people read the source code of these crates to learn, they begin to use these unnamed patterns in their code. I’ll mention (and credit) some of these in later chapters.
You may not invent patterns that become famous, but I hope that I can help you to think in Rust, and by doing so, know hundreds of useful patterns that have no names and be able to discover hundreds more.
In the next section, we’ll discuss our first coding project and how it will help illustrate what not to do when working with Rust.
Let’s build a calculator, badly!
Section titled “Let’s build a calculator, badly!”In this section, we’ll build a calculator application, similar to examples found in many tutorials. We’ll call it Bad Calculator because we’ll be intentionally building it badly.
To illustrate the value of using patterns and practices centered on Rust, we’ll see what happens when we don’t do that. As we’ve discussed, using design patterns that originate from paradigms that can’t be expressed properly in Rust, such as object orientation, leads to systemic issues with the code we write and the applications we build. Our Bad Calculator will showcase these issues.
We’ll do the following:
- Design it around paradigms that don’t work in Rust
- Use patterns and techniques that don’t fit
- Try to overcome errors by working around them
- Try to trick the borrow checker into doing what we want
While doing so, we’ll discuss the roadblocks that we run into and why we’re facing them. We’ll also discuss what we should have done, and how we should have been thinking about what we’re building.
For the sake of simplicity, we won’t be using any crates in this project. We want to make our own mistakes!
In this chapter, all we’ll do is create the project and create a very simple main loop. We’ll be filling in all of our (bad) logic in later chapters.
Let’s begin by creating the Cargo project itself. Switch to whatever directory you want to keep your project code in and initialize the project. We’ll use cargo new to create a new application in a directory called bad_calculator:
$ cargo new bad_calculatorCreating binary (application) `bad_calculator` packageYour directory structure should now look like this:
bad_calculator├── Cargo.toml└── src └── main.rsFor now, we’ll just create the main loop. In this loop, we’ll read user input, evaluate it in a function that we’ll write later, and print the result until the user types “exit” as input. Edit main.rs so that it looks like this:
use std::io::Write;use std::process::exit;
fn evaluate_expression(expression: &str) -> Result<String, String> { todo!()}
fn main() { let mut buf = String::new(); loop { print!("> "); std::io::stdout().flush().unwrap();
buf.clear();
std::io::stdin().read_line(&mut buf).unwrap();
if buf.trim() == "exit" { exit(0); }
match evaluate_expression(&buf) { Ok(result) => println!("{result}"), Err(error) => println!("Error: {error}"), } }}Summary
Section titled “Summary”In this chapter, we discussed why developing code in Rust requires new patterns, new practices, and new thinking. First, we discussed why traditional design patterns, while extremely helpful in many languages, need to be revised and expanded when working with Rust. Then, we talked about hitting the wall in your Rust journey, and the reasons why, as the complexity of projects rises, Rust can suddenly feel much more painful to work with. After that, we discussed the unusual learning curve of Rust development. Following that, we discussed what it means to think in Rust, why it’s key to Rust development, and how Rust design patterns can help. Finally, we discussed the project that we’ll be building in the following chapters, a calculator built by ignoring Rust patterns and practices.
Using what we’ve learned in this chapter, you’ll be able to recognize situations where compiler errors or awkward workarounds are signs that you’re not using the correct patterns. You’ll also be able to identify why your progress in learning Rust is not smooth and progressive. Most importantly, you now have a foundation for understanding the issues with the anti-patterns in upcoming chapters, the value of the new patterns throughout this book, and the new thinking they represent.
In the next chapter, we’ll begin discussing Rust anti-patterns, starting with trying to work with Rust in an object-oriented style. We’ll also continue to work on our Bad Calculator.