Skip to content

Commit b33f5fc

Browse files
nimrod-starkwareStavbe
authored andcommitted
Rust enums
1 parent 06221a3 commit b33f5fc

File tree

3 files changed

+785
-0
lines changed

3 files changed

+785
-0
lines changed

blocks_pdf/enums.pdf

59.9 KB
Binary file not shown.

blocks_typ/enums.typ

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#import "../src/block_by_block.typ": *
2+
3+
#set page(
4+
margin: (
5+
top: 30pt,
6+
bottom: 0pt,
7+
left: 50pt,
8+
right: 50pt,
9+
),
10+
// Choose your block color here
11+
background: [#page_border(blue)],
12+
)
13+
// Do not change the font size.
14+
#set text(size: 13pt)
15+
#logo("enums")
16+
#block_header(7, [Rust enums are great!])\
17+
#what
18+
\ Everyone knows what enums are — but knowing when to use them isn’t always obvious.
19+
\ Here’s the rule of thumb: if your type can only take on a few known values, you should enum it.\
20+
#why
21+
\ Enums make your code self-documenting, more readable, and give the compiler a chance to catch your bugs before your teammate does.\
22+
#how
23+
#bad_code[```rust
24+
struct LoggingConfig {
25+
enabled: bool,
26+
// If not enabled, we don't know the level.
27+
level: Option<LogLevel>,
28+
}
29+
impl LoggingConfig {
30+
fn log(&self, message: &str) {
31+
if self.enabled {
32+
// Why taking the risk of panicking here?
33+
let level = self.level.unwrap();
34+
log(level, message);
35+
}
36+
}
37+
}
38+
```]
39+
Let's just enum it:
40+
#good_code[```rust
41+
enum LoggingConfig {
42+
Disabled,
43+
Enabled(LogLevel),
44+
}
45+
impl LoggingConfig {
46+
fn log(&self, message: &str) {
47+
if let Self::Enabled(level) = self { // No risk of panicking.
48+
log(level, message);
49+
}
50+
}
51+
}
52+
```]
53+
#tip[
54+
Planning to (de)serialize? Reach for a struct, not an enum.
55+
Enums tend to confuse other languages.
56+
]
57+
#v(-20pt)
58+
#slack

0 commit comments

Comments
 (0)