You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/idiomatic/leveraging-the-type-system/typestate-pattern.md
+12-4Lines changed: 12 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,8 +4,7 @@ minutes: 15
4
4
5
5
## Typestate Pattern
6
6
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.
9
8
10
9
```rust
11
10
# usestd::fmt::Write;
@@ -52,10 +51,19 @@ fn main() {
52
51
- The typestate pattern allows us to model state machines using Rust’s type
53
52
system. In this case, the state machine is a simple serializer.
54
53
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
57
56
states happen by consuming one value and producing another.
0 commit comments