| Type | Value range | # values |
|---|---|---|
bool
|
true, false
|
2 |
u8
|
0, 1, …, 255
|
256 |
i8
|
-127, -126, …, -1, 0, 1, …, 128
|
256 |
Students?4
Professors?512
Outfits?\(2^{24}=16777216\)
\[ |A \times B| = |A| \times |B| \]
\[ |A \times B \times \dots \times N| = \prod_{i \in \{A,B,...,N\}}^{} |i| \]
Write a struct for a traffic light with exactly three states: Red, yellow, green
Discuss with your neighbor for 2 minutes!
| Type | Value range | # values |
|---|---|---|
bool
|
true, false
|
2 |
u8
|
0, 1, …, 255
|
256 |
i8
|
-127, -126, …, -1, 0, 1, …, 128
|
256 |
enumenum with data\[ |A + B| = |A| + |B| \]
struct or enum?null in Rustenums are perfect to model the absence of a value:Maybe monad)Option<T> is coolenum is only part of the equation, the other half is called pattern matching:Option<T>enum on the hardware levelenum?enum on the hardware level (cont.)enum in Rust is a discriminated union (also called tagged union)N=sizeof(tag)
M=sizeof(biggest variant)

Option<T> zero-overhead?std::mem::size_of:| Type | Size (bytes) | Size of T + bool |
|---|---|---|
Option<i32> |
8 |
5 |
Option<NonZeroI32> |
4 |
5 |
Option<bool> |
1 |
2 |
Option<&i32> |
8 |
9 |
Option<T>, the compiler can use this niche as the discriminant:
0 for Option<NonZeroI32>null for Option<&T>Option<T> usageOption<T>Option::map is a higher order function: A function taking a function:Option<T> is consumed (first argument of type self)TU by valueOption<T> cheat sheet