I have some function read()
which can fail in multiple ways or return one of several variations.
I am considering if I should use a Result
with two enums as the payloads (right word?) so I get all the sugar with Result. Or, should I create my own single enum with all error/success states and avoid having to "double match" the function's return value.
I have seen both patterns in the wild, and glean that the standard library really always uses Result.
Is there a best practice/recommendation/idiom here?
An Example:
enum StreamResult {
// All of these would have data, but for simplicity . . .
Message,
Batch,
SocketError,
StreamError,
}
fn read() -> StreamResult {
// Do stuff and return a result
}
fn main() {
let result = read();
match result {
// Now, I have to match on all four variants
}
}
This has a single match. It's nice and clean. But, the Error and Success states are mixed. I cannot use unwrap()
or the ?
or any other fun things with Result
Or:
enum StreamSuccess {
Message,
Batch,
}
enum StreamError {
SocketError,
StreamError,
}
fn read() -> Result<StreamSuccess, StreamError> {
// Do stuff and return a result
}
fn main() {
let result = read();
match result {
Ok(success) => {
match success {
// Now, I match both variants
}
},
Err(error) => {
match error {
// Now, I match both variants
}
}
}
}
This is uglier to call, but allows for unwrap() or ? or many other niceties.
Thank you for your input! I really appreciate learning to write idiomatically.