Description
Feature gate: #![feature(option_result_unwrap_unchecked)]
This is a tracking issue for the unchecked variants of unwrap()
and unwrap_err()
of Option
and Result
.
These are unsafe functions intended to be used in hot paths of performance sensitive applications where the variant an Option
/Result
holds is known, allowing to skip the branch that the safe version introduces. They complement other *_unchecked()
methods already available, such as get_unchecked()
in slices.
Public API
impl<T> Option<T> {
pub unsafe fn unwrap_unchecked(self) -> T;
}
impl<T, E> Result<T, E> {
pub unsafe fn unwrap_unchecked(self) -> T;
pub unsafe fn unwrap_err_unchecked(self) -> E;
}
Steps / History
- Implementation: Add
unwrap_unchecked()
methods forOption
andResult
#80876 - Stabilization report: Tracking Issue for
option_result_unwrap_unchecked
#81383 (comment) - Final commenting period (FCP): Tracking Issue for
option_result_unwrap_unchecked
#81383 (comment) - Stabilization PR: Stabilize
option_result_unwrap_unchecked
#89951
Unresolved Questions
-
Should we add
expect_unchecked
, and if yes, do it within another feature flag, to unblockunwrap_unchecked
? Tracking Issue foroption_result_unwrap_unchecked
#81383 (comment)- It seems best to have it under another feature flag to avoid blocking this one.
-
Should we panic on failure in debug (i.e. for those projects that build
core
themselves)? If yes, that would mean there is no way to actually remove the check for those projects, which could be potentially needed by someone. If we do, should it be documented? Tracking Issue foroption_result_unwrap_unchecked
#81383 (comment)- The current implementation uses
debug_assert!
, which may be useful for projects that buildcore
with debug assertions enabled (e.g. the bors test suite or some embedded projects), but this is not documented, and indeed most users will not see such behavior, sincecore
is shipped in release mode. - Furthermore, since it is UB anyway, we have room for changing the implementation, e.g. if we end up distributing the standard library with debug assertions enabled for some use cases.
- The current implementation uses
-
Should we name them
unchecked_unwrap
instead? Tracking Issue foroption_result_unwrap_unchecked
#81383 (comment).- The current name (
unwrap_unchecked
) follows the convention of other stable methods in the standard library such asget_unchecked
,map_unchecked
,new_unchecked
,unreachable_unchecked
... (see as well https://rust-lang.github.io/api-guidelines/naming.html#getter-names-follow-rust-convention-c-getter). - On the other hand, the
unchecked_{add,...}
methods seem to follow the opposite convention, but those are unstable and they likely do it because the stable{checked,...}_{add,...}
exist.
- The current name (