1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-08-08 08:22:52 +02:00

apply part of feedback

This commit is contained in:
Glen De Cauwsemaecker
2025-08-02 11:18:05 +02:00
parent 602ef859ba
commit 4b0870eb35

View File

@ -4,8 +4,7 @@ minutes: 15
## Typestate Pattern ## Typestate Pattern
The typestate pattern uses Rust’s type system to make **invalid states Typestate is the practice of encoding a part of the state of the value in its type, preventing incorrect or inapplicable operations from being called on the value.
unrepresentable**.
```rust ```rust
# use std::fmt::Write; # use std::fmt::Write;
@ -52,10 +51,19 @@ fn main() {
- The typestate pattern allows us to model state machines using Rust’s type - The typestate pattern allows us to model state machines using Rust’s type
system. In this case, the state machine is a simple serializer. system. In this case, the state machine is a simple serializer.
- The key idea is that each state in the process, starting a struct, writing - The key idea is that at each state in the process, we can only
fields, and finishing, is represented by a different type. Transitions between do the actions which are valid for that state. Transitions between
states happen by consuming one value and producing another. states happen by consuming one value and producing another.
```bob
+------------+ serialize struct +-----------------+
| Serializer +-------------------->| SerializeStruct |<-------+
+------------+ +-+-----+---------+ |
^ | | |
| finish struct | | serialize field |
+-----------------------------+ +------------------+
```
- In the example above: - In the example above:
- Once we begin serializing a struct, the `Serializer` is moved into the - Once we begin serializing a struct, the `Serializer` is moved into the