Skip to content

Commit 69edf8e

Browse files
committed
Suggest Default::default() for struct literals with private fields
1 parent be0958f commit 69edf8e

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

compiler/rustc_hir_typeck/src/expr.rs

+17
Original file line numberDiff line numberDiff line change
@@ -2165,6 +2165,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21652165
);
21662166
}
21672167
}
2168+
if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2169+
&& self.infcx
2170+
.type_implements_trait(default_trait, [adt_ty], self.param_env)
2171+
.may_apply()
2172+
{
2173+
err.multipart_suggestion(
2174+
"consider using the `Default` trait",
2175+
vec![
2176+
(span.shrink_to_lo(), "<".to_string()),
2177+
(
2178+
span.shrink_to_hi().with_hi(expr_span.hi()),
2179+
" as std::default::Default>::default()".to_string(),
2180+
),
2181+
],
2182+
Applicability::MaybeIncorrect,
2183+
);
2184+
}
21682185
}
21692186

21702187
err.emit();

tests/ui/privacy/suggest-box-new.stderr

+8
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ LL | let _ = std::collections::HashMap::with_hasher(_);
6767
| ~~~~~~~~~~~~~~~~
6868
LL | let _ = std::collections::HashMap::with_capacity_and_hasher(_, _);
6969
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70+
help: consider using the `Default` trait
71+
|
72+
LL | let _ = <std::collections::HashMap as std::default::Default>::default();
73+
| + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7074

7175
error: cannot construct `Box<_, _>` with struct literal syntax due to private fields
7276
--> $DIR/suggest-box-new.rs:18:13
@@ -86,6 +90,10 @@ LL | let _ = Box::new_zeroed();
8690
LL | let _ = Box::new_in(_, _);
8791
| ~~~~~~~~~~~~~~
8892
and 10 other candidates
93+
help: consider using the `Default` trait
94+
|
95+
LL | let _ = <Box as std::default::Default>::default();
96+
| + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8997

9098
error: aborting due to 4 previous errors
9199

0 commit comments

Comments
 (0)