Skip to content

Commit 9386e14

Browse files
committed
fix the issue of suggest unwrap/expect for shorthand field
1 parent e06c94d commit 9386e14

File tree

4 files changed

+75
-0
lines changed

4 files changed

+75
-0
lines changed

Diff for: compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1811,6 +1811,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18111811
".expect(\"REASON\")",
18121812
)
18131813
};
1814+
1815+
let sugg = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {
1816+
Some(ident) => format!(": {ident}{sugg}"),
1817+
None => sugg.to_string(),
1818+
};
1819+
18141820
err.span_suggestion_verbose(
18151821
expr.span.shrink_to_hi(),
18161822
msg,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// run-rustfix
2+
#![allow(unused, dead_code)]
3+
4+
#[derive(Clone, Copy)]
5+
struct Stuff {
6+
count: i32,
7+
}
8+
struct Error;
9+
10+
fn demo() -> Result<Stuff, Error> {
11+
let count = Ok(1);
12+
Ok(Stuff { count: count? }) //~ ERROR mismatched types
13+
}
14+
15+
fn demo_unwrap() -> Stuff {
16+
let count = Some(1);
17+
Stuff { count: count.expect("REASON") } //~ ERROR mismatched types
18+
}
19+
20+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// run-rustfix
2+
#![allow(unused, dead_code)]
3+
4+
#[derive(Clone, Copy)]
5+
struct Stuff {
6+
count: i32,
7+
}
8+
struct Error;
9+
10+
fn demo() -> Result<Stuff, Error> {
11+
let count = Ok(1);
12+
Ok(Stuff { count }) //~ ERROR mismatched types
13+
}
14+
15+
fn demo_unwrap() -> Stuff {
16+
let count = Some(1);
17+
Stuff { count } //~ ERROR mismatched types
18+
}
19+
20+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/issue-118145-unwrap-for-shorthand.rs:12:16
3+
|
4+
LL | Ok(Stuff { count })
5+
| ^^^^^ expected `i32`, found `Result<{integer}, _>`
6+
|
7+
= note: expected type `i32`
8+
found enum `Result<{integer}, _>`
9+
help: use the `?` operator to extract the `Result<{integer}, _>` value, propagating a `Result::Err` value to the caller
10+
|
11+
LL | Ok(Stuff { count: count? })
12+
| ++++++++
13+
14+
error[E0308]: mismatched types
15+
--> $DIR/issue-118145-unwrap-for-shorthand.rs:17:13
16+
|
17+
LL | Stuff { count }
18+
| ^^^^^ expected `i32`, found `Option<{integer}>`
19+
|
20+
= note: expected type `i32`
21+
found enum `Option<{integer}>`
22+
help: consider using `Option::expect` to unwrap the `Option<{integer}>` value, panicking if the value is an `Option::None`
23+
|
24+
LL | Stuff { count: count.expect("REASON") }
25+
| ++++++++++++++++++++++++
26+
27+
error: aborting due to 2 previous errors
28+
29+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)