Skip to content

Commit 3a92b99

Browse files
committed
Auto merge of #74956 - ecstatic-morse:const-option-unwrap, r=oli-obk
Make `Option::unwrap` unstably const This is lumped into the `const_option` feature gate (#67441), which enables a potpourri of `Option` methods. cc @rust-lang/wg-const-eval r? @oli-obk
2 parents ac91673 + 96c84ac commit 3a92b99

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

library/core/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
#![feature(const_fn_union)]
8282
#![feature(const_generics)]
8383
#![feature(const_option)]
84+
#![feature(const_precise_live_drops)]
8485
#![feature(const_ptr_offset)]
8586
#![feature(const_ptr_offset_from)]
8687
#![feature(const_raw_ptr_comparison)]

library/core/src/option.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,8 @@ impl<T> Option<T> {
380380
#[inline]
381381
#[track_caller]
382382
#[stable(feature = "rust1", since = "1.0.0")]
383-
pub fn unwrap(self) -> T {
383+
#[rustc_const_unstable(feature = "const_option", issue = "67441")]
384+
pub const fn unwrap(self) -> T {
384385
match self {
385386
Some(val) => val,
386387
None => panic!("called `Option::unwrap()` on a `None` value"),

src/test/ui/consts/const-unwrap.rs

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// check-fail
2+
3+
#![feature(const_option)]
4+
5+
const FOO: i32 = Some(42i32).unwrap();
6+
7+
// This causes an error, but it is attributed to the `panic` *inside* `Option::unwrap` (maybe due
8+
// to `track_caller`?). A note points to the originating `const`.
9+
const BAR: i32 = Option::<i32>::None.unwrap(); //~ NOTE
10+
11+
fn main() {
12+
println!("{}", FOO);
13+
println!("{}", BAR);
14+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: any use of this value will cause an error
2+
--> $SRC_DIR/core/src/option.rs:LL:COL
3+
|
4+
LL | None => panic!("called `Option::unwrap()` on a `None` value"),
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
| |
7+
| the evaluated program panicked at 'called `Option::unwrap()` on a `None` value', $DIR/const-unwrap.rs:9:38
8+
| inside `std::option::Option::<i32>::unwrap` at $SRC_DIR/core/src/macros/mod.rs:LL:COL
9+
| inside `BAR` at $DIR/const-unwrap.rs:9:18
10+
|
11+
::: $DIR/const-unwrap.rs:9:1
12+
|
13+
LL | const BAR: i32 = Option::<i32>::None.unwrap();
14+
| ----------------------------------------------
15+
|
16+
= note: `#[deny(const_err)]` on by default
17+
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
18+
19+
error: aborting due to previous error
20+

0 commit comments

Comments
 (0)