Suggest Default::default() for struct literals with private fields

This commit is contained in:
Esteban Küber 2023-11-08 23:56:16 +00:00
parent be0958f5ab
commit 69edf8e784
2 changed files with 25 additions and 0 deletions

View File

@ -2165,6 +2165,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
}
}
if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
&& self.infcx
.type_implements_trait(default_trait, [adt_ty], self.param_env)
.may_apply()
{
err.multipart_suggestion(
"consider using the `Default` trait",
vec![
(span.shrink_to_lo(), "<".to_string()),
(
span.shrink_to_hi().with_hi(expr_span.hi()),
" as std::default::Default>::default()".to_string(),
),
],
Applicability::MaybeIncorrect,
);
}
}
err.emit();

View File

@ -67,6 +67,10 @@ LL | let _ = std::collections::HashMap::with_hasher(_);
| ~~~~~~~~~~~~~~~~
LL | let _ = std::collections::HashMap::with_capacity_and_hasher(_, _);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
help: consider using the `Default` trait
|
LL | let _ = <std::collections::HashMap as std::default::Default>::default();
| + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: cannot construct `Box<_, _>` with struct literal syntax due to private fields
--> $DIR/suggest-box-new.rs:18:13
@ -86,6 +90,10 @@ LL | let _ = Box::new_zeroed();
LL | let _ = Box::new_in(_, _);
| ~~~~~~~~~~~~~~
and 10 other candidates
help: consider using the `Default` trait
|
LL | let _ = <Box as std::default::Default>::default();
| + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 4 previous errors