Lately I've been thinking a lot about the patterns and structures which we program with. It's really wonderful to start exploring a project and see familiar patterns and styles which you've already used before. It makes it easier to understand the project, and empowers you to start working on the project faster. Sometimes you're working on a new project and realize that you need to do something in the same way as you did in another project. This thing might not be a functionality or a library, it might not be something which you can encode into some clever macro or small crate. Instead, it may be simply a pattern, or a structural concept which addresses a problem nicely. One interesting pattern that is commonly applied to problems is that of the 'State Machine'. Let's take some time to consider what exactly we mean when we say that, and why they're interesting. Throughout this post you can run all examples in the playground, I typically use 'Nightly' out of habit. There are a lot of resources and topical articles about state machines out there on the internet. Even more so, there are a lot of implementations of state machines. Just to get to this web page you used one. You can model TCP as a state machine. You can model HTTP requests with one too. You can model any regular language, such as a regex, as a state machine. They're everywhere, hiding inside things we use every day. So, a State Machine is any 'machine' which has a set of 'states' and 'transitions' defined between them. When we talk about a machine we're referring to the abstract concept of something which does something. For example, your 'Hello World!' function is a machine. It is started and eventually outputs what we expect it to. Some model which you use to interact with your database is just the same. We'll regard our most basic machine simply as a struct that can be created and destroyed. struct Machine; fn main() { let my_machine = Machine; } States are a way to reason about where a machine is in i...
First seen: 2025-04-20 04:22
Last seen: 2025-04-20 17:25