4 ms·
My favourite never type ability is when you need to conform to a trait that returns Result but your specific implementation can never produce an error. Return
by cipherjim 22d ago
My favourite never type ability is when you need to conform to a trait that returns Result but your specific implementation can never produce an error.
Return Result<T, !> and the compiler knows that callers never have to check the error case because by definition it can’t be constructed.
- tialaramex 22d agoAnd if your callers are generic over the error type, and so they do have code for handling errors, the compiler won't emit this code for your result type because you've said its error type can't exist.
- tyre 22d agoDoes that mean you can assign the result of the function without explicitly unwrapping? Or that the compiler removes the call to unwrap? Or neither?
- bonzini 22d agoYou need to unwrap but the compiler removes the call. If instead you know that the callee is infallible you can also do let Ok(x) = call_that_cant_fail();
- pascahousut 22d agoMy first encounter will likely be the opposite, i.e. a call that will only produce a Result::Err if anything, and never a Result:Ok. I've made programs where there are a bunch of continuously running jobs that should never terminate in the happy scenario. If any of these jobs terminate, it'll be due to some sort of failure, and so Result<!, MyError> seems like a reasonable return type for such job. I think I've already used the Infallible in there but I think this being part of the language now makes the code feel more correct or clean or something like that.