Skip to content

Commit 158b2a2

Browse files
Rust enums
1 parent 5a057a7 commit 158b2a2

File tree

3 files changed

+792
-0
lines changed

3 files changed

+792
-0
lines changed

blocks_pdf/enums.pdf

59.9 KB
Binary file not shown.

blocks_typ/enums.typ

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#import "../src/block_by_block.typ": *
2+
3+
#set page(
4+
margin: (
5+
top: 20pt,
6+
bottom: 0pt,
7+
left: 50pt,
8+
right: 50pt,
9+
),
10+
background: [#page_border(blue)],
11+
)
12+
#set text(size: 12.0pt)
13+
14+
#logo("enums")
15+
16+
#block_header(7, [Rust enums are great!])
17+
18+
#what
19+
\ Rust enums let you encode valid states in the type system, these states are enforced at compilation time.
20+
21+
#why
22+
\ The compiler then enforces correctness: you can’t create invalid combinations of fields, you avoid runtime checks and redundancy.
23+
24+
#how
25+
#bad_code[```rust
26+
struct LoggingConfig {
27+
enabled: bool,
28+
level: LogLevel, // What should be here when logging is disabled?
29+
}
30+
```]
31+
Let's try to make it optional!
32+
#bad_code[```rust
33+
struct LoggingConfig {
34+
enabled: bool,
35+
level: Option<LogLevel>,
36+
}
37+
impl LoggingConfig {
38+
fn log(&self, message: &str) {
39+
if self.enabled {
40+
// Why taking the risk of panicking here?
41+
let level = self.level.unwrap();
42+
log(level, message);
43+
}
44+
}
45+
}
46+
```]
47+
We should do that instead!
48+
#code[```rust
49+
enum LoggingConfig {
50+
Disabled,
51+
Enabled(LogLevel),
52+
}
53+
impl LoggingConfig {
54+
fn log(&self, message: &str) {
55+
if let Self::Enabled(level) = self { // No risk of panicking.
56+
log(level, message);
57+
}
58+
}
59+
}
60+
```]
61+
#tip[
62+
You should consider using structs over enums for (de)serializable objects, as the schema for enums is less compatible with other programming languages (e.g Python).
63+
]
64+
#v(-32pt)
65+
#slack

0 commit comments

Comments
 (0)