Description
I was teaching a newbie some Rust, and doing the usual hand-waving about error handling using unwrap. They asked what 'unwrap' means. I said look it up in the docs. The docs read (paraphrased) "unwrap unwraps". I was embarrassed.
#68918 Don't use the word "unwrap" to describe "unwrap" methods
The English word "unwrap" is used in the name of numerous methods in core
and std
, but is not defined by the documentation and does not have a commonly accepted concrete definition in computer science. The everyday concept of "unwrapping" is not detailed enough to resolve questions about the precise meaning of the term as it is used in Rust.
Existing methods:
methods | |
---|---|
Result |
unwrap , unwrap_or , unwrap_or_else , unwrap_or_default , unwrap_err |
Option |
unwrap , unwrap_or , unwrap_or_else , unwrap_or_default , unwrap_none (unstable) |
Rc |
try_unwrap |
Arc |
try_unwrap |
Based on this existing usage, I propose a definition:
An "unwrap" method in Rust extracts an underlying value from one or more containers, consumes the container(s), and returns an owned value.
Result::unwrap()
andOption::unwrap()
(and their variants) unwrap two containers in one step: The abstractResult
orOption
itself, and the concreteOk
orSome
tuple variant inside. You might think ofunwrap
as being shorthand for "unwrap_ok" and "unwrap_some", though these methods do not exist.
Result::unwrap_err()
andOption::unwrap_none()
(nightly only) express that theErr
orNone
variants are expected instead, and that those containers are the ones that should be unwrapped.
Outstanding questions: Where is the most appropriate place to put a definition of "unwrap"? Is The Book canonical?
Previous discussion in:
#62633 Tracking issue for Option::expect_none(msg) and unwrap_none()
#73077 Stabilize Option::expect_none(msg) and Option::unwrap_none()
#77326 Stabilize Option::unwrap_none
and Option::expect_none
#68849 Don't use the word 'unwrap' to describe core 'unwrap' functions
#68918 Don't use the word "unwrap" to describe "unwrap" methods
#23713 Make Option.unwrap documentation more precise
#19149 Rename unwrap functions to into_inner
#430 RFC: Finalizing more naming conventions
etc...