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
\ 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).
0 commit comments