I am trying to pass a function to unwrap_or_else to handle errors where I either exit or panic. The example in the playground here should elaborate.
I can't seem to be able to make the compiler happy, since it expects a function that returns a type other than !. I thought this is precisely where I would use the Never type. Why is this the case? Do you have any suggestion for an alternative way to achieve this (aside from simply passing in the same closure everytime)?
I like this. But I don't get how this is possible, and not the one I tried. So, in this, the compiler can infer that we have only one variant left (from the return type of handle_cancellation), but in the case with the unwrap_or_else it cannot infer that the function never returns and we don't need a string.
I don't know the internals, but it seems like it's not able to ignore the never type in a generic context. unwrap_or_else requires the return type to be the same as otherwise. Thinking about it like that, I realized that this also works:
fn handle_cancellation<T>(e: Error) -> T {
Here, we pretend that it's going to return whatever we ask it to.
The problem is that the closure passed to unwrap_or_else returns T, and your closure doesn't do that. We can fix that and return T but then we're not using the never type. playground
It's not about inference, it's about type signatures and bounds. ! is a concrete type,[1] and your OP function returned !. But unwrap_or_else requires a function that returns String.
You get the same sort of error here, for example, even though &[(); 0] can coerce to &[()].