Context on unwrap()

It seems like an easy usability feature would be context information on unwrap().

Right now if you unwrap(), the panic produces the message that comes from the error type you’re unwrapping (or simply that you tried to unwrap a None). I would like to see the compiler inject source file and line of the actual call to unwrap.

Why? It’s generally impossible to track down where the unwrap occurred unless you have debugging enabled (not always possible). I imagine that a lot of us have reluctantly had to go through their code replacing all their unwrap()s to expect()s.

Runtime cost would be that an extra binary string would be stored in the executable. No other performance penalty.

1 Like

Is this not fulfilled by RUST_BACKTRACE?

No, RUST_BACKTRACE outputs the context according to the debugging information which may not be present. A backtrace is certainly less readable than something like the error of the form: unwrap() of None,

Edit: Also RUST_BACKTRACE has a runtime penalty whereas my suggestion doesn’t.

RFC 2091 specifies a design to fix this. This RFC has been accepted, but not yet implemented.


Yes, that seems to be exactly it.

Exactly. Leading to unwrap never being used by “a lot of us” ever again.

Imho unwrap should never have existed as such, to begin with. It should have taken a string argument like expect does, so that people wanting to shoot themselves by not adding context information would have had to feed an empty string as an argument. And for people coming from other languages, feeding an empty string error message “smells” more than using a builtin ::core function of the language.

And with expect the code reads weirdly:

// No, this does not expect an unitialised parameter; quite the opposite!
let x = param.expect("Uninitialised parameter `param`");

// vs
let x = param.unwrap("Uninitialised parameter `param`");

Although I am perfectly aware that it is now too late to change that, we should keep in mind that deprecating unwrap remains in the realm of possibilities.

1 Like

I would recommend to write something like this instead:

let x = param.expect("retrieve initialised parameter `param`");