Skip to content

Commit 20c8fa3

Browse files
committed
docs: WIP - Add Enum concept documentation and expand Result enum docs
1 parent 7e82c0a commit 20c8fa3

File tree

3 files changed

+160
-3
lines changed

3 files changed

+160
-3
lines changed

journals/2025_11_27.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
## Learning Rust
2-
- [[Rust/Book/TRPL/Interactive]]
3-
- [[Rust/Book/CLR]]
4-
- author [[Person/Ken Youens-Clark]]
2+
- [[Rust/Book/CLR]] a few deprecations
3+
- author [[Person/Ken Youens-Clark]]
4+
- [[Rust/Book/TRPL/Interactive]] started working through this
5+
- [[rustup]] is the version manager for [[Rust]]
6+
- [[rustfmt]]
7+
- [[rustfix]]
8+
- [[cargo/clippy]]
9+
- [[cargo]]
10+
- [[Rust/prelude]]
11+
- [[Rust/use]]
12+
- [[Rust/std/result/Result]] - expanded with comprehensive documentation on the Result enum, its variants, methods, and usage patterns
13+
- [[Programming/Enum]] - created documentation for the general enum concept, covering benefits, use cases, and implementations across multiple languages

pages/Programming___Enum.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
- # Enum
2+
- Also known as: enumeration, enumerated type
3+
- A distinct data type that consists of a set of named constants, representing a collection of related values
4+
- Each named constant is called a `variant` (in some languages) or `enumerator`
5+
- ## Key Benefits
6+
- ### Improved Readability and Maintainability
7+
- Using descriptive names instead of arbitrary numbers or strings makes code more self-explanatory
8+
- Example: `Color.RED` is clearer than using `0` to represent a color
9+
- ### Type Safety
10+
- Restricts variables to predefined values, reducing the risk of invalid assignments
11+
- Ensures only valid, expected values are used, preventing bugs
12+
- ### Encapsulation
13+
- Groups related constants within a single data type
14+
- Organizes code more effectively and reduces errors from using unrelated constants
15+
- ## Common Use Cases
16+
- **State Management**: Representing discrete states (e.g., `PENDING`, `IN_PROGRESS`, `COMPLETED`)
17+
- **Configuration Options**: Defining sets of options or modes (e.g., logging levels: `DEBUG`, `INFO`, `WARNING`, `ERROR`)
18+
- **Control Flow**: Using enums in `switch` or `case` statements to handle different scenarios
19+
- **Error Handling**: Representing success/failure states (e.g., `Result<T, E>` in Rust)
20+
- **Nullable Values**: Representing optional values (e.g., `Option<T>` in Rust, `Optional<T>` in Java)
21+
- ## Language Implementations
22+
- ### C
23+
- Declared using the `enum` keyword
24+
- Creates a set of named integer constants
25+
- By default, values start at 0 and increment
26+
- ~~~c
27+
enum Color { RED, GREEN, BLUE };
28+
// RED = 0, GREEN = 1, BLUE = 2
29+
~~~
30+
- ### C++
31+
- Supports unscoped enums (similar to C)
32+
- C++11 introduced scoped enums with `enum class` for better type safety
33+
- Prevents implicit conversions
34+
- ~~~cpp
35+
enum class Color { RED, GREEN, BLUE };
36+
// Access: Color::RED
37+
~~~
38+
- ### Java
39+
- More robust enums that can have methods and fields
40+
- Can implement interfaces
41+
- Each enumerator is an instance of the enum type
42+
- ~~~java
43+
public enum Day {
44+
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
45+
THURSDAY, FRIDAY, SATURDAY;
46+
}
47+
~~~
48+
- ### Python
49+
- Provided by the `enum` module
50+
- Enumerators can have custom values
51+
- Supports iteration
52+
- ~~~python
53+
from enum import Enum
54+
55+
class Color(Enum):
56+
RED = 1
57+
GREEN = 2
58+
BLUE = 3
59+
~~~
60+
- ### Rust
61+
- Powerful enums that can hold data (sum types / tagged unions)
62+
- Each variant can have associated data
63+
- Used extensively for error handling and optional values
64+
- ~~~rust
65+
enum Result<T, E> {
66+
Ok(T),
67+
Err(E),
68+
}
69+
~~~
70+
- ## Considerations
71+
- ### Serialization
72+
- When storing or transmitting enum values, ensure consistent representation (integer, string, etc.)
73+
- All parts of the system must understand the chosen representation
74+
- ### Extensibility
75+
- Adding new values can affect existing code
76+
- `switch` or `match` statements without default cases may need updates
77+
- Plan for potential extensions to avoid maintenance challenges
78+
- ## Related
79+
- [[Rust/std/result/Result]] - Example of a powerful enum in Rust
80+
- [[Programming/Language/Feature]] - Language features in general
81+
- Type safety and type systems
82+
- Sum types / Tagged unions (in functional programming languages)
83+
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Result<T, E>
2+
- A fundamental [[Programming/Enum]] in [[Rust]] used for error handling, representing either success or failure
3+
- Part of [[Rust/prelude]], so it's automatically imported
4+
- Defined in `std::result::Result`
5+
- ## Definition
6+
- ~~~rust
7+
enum Result<T, E> {
8+
Ok(T),
9+
Err(E),
10+
}
11+
~~~
12+
- `T` - the type of the value in the `Ok` variant
13+
- `E` - the type of the error in the `Err` variant
14+
- ## Variants
15+
- ### Ok(T)
16+
- Represents a successful operation
17+
- Contains the successful value of type `T`
18+
- ### Err(E)
19+
- Represents a failed operation
20+
- Contains error information of type `E`
21+
- ## Common Methods
22+
- ### Checking Variants
23+
- `is_ok()` - returns `true` if the result is `Ok`
24+
- `is_err()` - returns `true` if the result is `Err`
25+
- ### Transforming Values
26+
- `map<U, F>(self, op: F) -> Result<U, E>` - maps a `Result<T, E>` to `Result<U, E>` by applying a function to the contained `Ok` value
27+
- `map_err<F, O>(self, op: O) -> Result<T, F>` - maps a `Result<T, E>` to `Result<T, F>` by applying a function to the contained `Err` value
28+
- ### Chaining Operations
29+
- `and_then<U, F>(self, op: F) -> Result<U, E>` - calls `op` if the result is `Ok`, otherwise returns the `Err` value
30+
- `or_else<F, O>(self, op: O) -> Result<T, F>` - calls `op` if the result is `Err`, otherwise returns the `Ok` value
31+
- ### Unwrapping
32+
- `unwrap()` - returns the value if `Ok`, panics if `Err`
33+
- `unwrap_or(default: T) -> T` - returns the value if `Ok`, otherwise returns `default`
34+
- `unwrap_or_else<F>(op: F) -> T` - returns the value if `Ok`, otherwise calls `op` with the error
35+
- `expect(msg: &str) -> T` - returns the value if `Ok`, panics with `msg` if `Err`
36+
- ## Usage Patterns
37+
- ### Pattern Matching
38+
- Use `match` to handle both variants:
39+
- ~~~rust
40+
match result {
41+
Ok(value) => println!("Success: {:?}", value),
42+
Err(error) => println!("Error: {:?}", error),
43+
}
44+
~~~
45+
- ### The `?` Operator
46+
- Propagates errors up the call stack
47+
- If `Result` is `Err`, returns early with the error
48+
- If `Result` is `Ok`, unwraps the value
49+
- Can only be used in functions that return `Result`
50+
- ### Example Function
51+
- ~~~rust
52+
fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
53+
match header.get(0) {
54+
None => Err("invalid header length"),
55+
Some(&1) => Ok(Version::Version1),
56+
Some(&2) => Ok(Version::Version2),
57+
Some(_) => Err("invalid version"),
58+
}
59+
}
60+
~~~
61+
- They call each option of enum a `variant`
62+
- ## Related
63+
- [[Rust/prelude]] - Result is automatically imported
64+
- [[Rust/Option<T>]] - Similar enum for nullable values
65+
- Error handling in Rust typically uses Result for recoverable errors

0 commit comments

Comments
 (0)