3 ms·
From my perspective, these really are more like enums than unions. Rust enums cover C-style enums as a limiting case: enum Result { Ok, Err,
by Twisol 6y ago
From my perspective, these really are more like enums than unions. Rust enums cover C-style enums as a limiting case:
enum Result {
Ok,
Err,
}
If this was all you got, you'd need to return something like `(status, value, err)` to model fallible functions. This is not unlike Go's `value, err` convention, except that `status` is additionally inlined into `value` as a sentinel `nil`. This does nothing to prevent you from using the `value` if an error has occurred, or vice versa.
Instead, we like to carry data _alongside_ the enum tags:
// using named fields instead of tuple structs, for clarity
enum Result<T, E> {
Ok {value: T},
Err {err: E},
}
Now we can return a single `Result,` and you can only use `value` if the function succeeded, and you can only use `err` if the function failed.