Version of Result that always contains the data

some functions, like read_exact, would make more sense if their return value was always available, even if an error occurs

this is possible to express using a tuple, but then you lose out on most of the handy utility functions on result.

has anyone made a crate that expresses this semantic? you could even make it more general by having 3 "fields":

  • data if ok
  • data if err
  • data available in both cases

Assuming you mean std::io::Read::read_exact(), that returns io::Result<()>, i.e., the success value doesn't contain any information (and you can always make up a () out of thin air). What do you mean by "available"? It really seems to make no sense.

oh, i meant the number of bytes read.. perhaps Read::read would have been a better example.

I'm afraid not, as Read::read implementations must guarantee that there are no bytes read if an error is returned. From the docs:

If this function encounters any form of I/O or other error, an error variant will be returned. If an error is returned then it must be guaranteed that no bytes were read.

1 Like

it's not hard to imagine an alternative interface that doesn't make that guarantee, however.

One similar case from the standard library is LockResult which is Result<Guard, PoisonError<Guard>>, i.e. the error contains the same data as the success type.

Or binary_search which just returns Result<usize, usize>.

5 Likes

I have used: (ReturnType, Result<(), Error>)

It seems to me that it’s the error type’s responsibility to return possible partial etc data when it makes sense. No need for a three-way Result when you can simply compose

enum Error {
  GotSomeData(Data),
  SomeOtherError(…)
}

type Res = Result<Data, Error>;
2 Likes

the main problem with this is that extracting the common data requires a decently complex pattern match instead of a trivial field access.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.