Skip to content

Commit 4b0870e

Browse files
committed
apply part of feedback
1 parent 602ef85 commit 4b0870e

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/idiomatic/leveraging-the-type-system/typestate-pattern.md

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ minutes: 15
44

55
## Typestate Pattern
66

7-
The typestate pattern uses Rust’s type system to make **invalid states
8-
unrepresentable**.
7+
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.
98

109
```rust
1110
# use std::fmt::Write;
@@ -52,10 +51,19 @@ fn main() {
5251
- The typestate pattern allows us to model state machines using Rust’s type
5352
system. In this case, the state machine is a simple serializer.
5453

55-
- The key idea is that each state in the process, starting a struct, writing
56-
fields, and finishing, is represented by a different type. Transitions between
54+
- The key idea is that at each state in the process, we can only
55+
do the actions which are valid for that state. Transitions between
5756
states happen by consuming one value and producing another.
5857

58+
```bob
59+
+------------+ serialize struct +-----------------+
60+
| Serializer +-------------------->| SerializeStruct |<-------+
61+
+------------+ +-+-----+---------+ |
62+
^ | | |
63+
| finish struct | | serialize field |
64+
+-----------------------------+ +------------------+
65+
```
66+
5967
- In the example above:
6068

6169
- Once we begin serializing a struct, the `Serializer` is moved into the

0 commit comments

Comments
 (0)