Skip to content

Commit 573ebf0

Browse files
authored
Rollup merge of #138998 - rperier:donot_suggest_to_use_impl_trait_in_closure_params, r=Noratrieb
Don't suggest the use of `impl Trait` in closure parameter Fixes #138932
2 parents 9a9a078 + 8b6ff4a commit 573ebf0

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

Diff for: compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -3018,12 +3018,23 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
30183018
[] => span_bug!(ty.span, "trait object with no traits: {ty:?}"),
30193019
};
30203020
let needs_parens = traits.len() != 1;
3021-
err.span_suggestion_verbose(
3022-
span,
3023-
"you can use `impl Trait` as the argument type",
3024-
"impl ",
3025-
Applicability::MaybeIncorrect,
3026-
);
3021+
// Don't recommend impl Trait as a closure argument
3022+
if let Some(hir_id) = hir_id
3023+
&& matches!(
3024+
self.tcx.parent_hir_node(hir_id),
3025+
hir::Node::Item(hir::Item {
3026+
kind: hir::ItemKind::Fn { .. },
3027+
..
3028+
})
3029+
)
3030+
{
3031+
err.span_suggestion_verbose(
3032+
span,
3033+
"you can use `impl Trait` as the argument type",
3034+
"impl ",
3035+
Applicability::MaybeIncorrect,
3036+
);
3037+
}
30273038
let sugg = if !needs_parens {
30283039
vec![(span.shrink_to_lo(), format!("&{kw}"))]
30293040
} else {

Diff for: tests/ui/traits/dont-suggest-impl-as-closure-arg.rs

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Suggestion to use impl trait in closure parameter is invalid, see issue 138932
2+
fn main() {
3+
let c = |f: dyn Fn()| f();
4+
//~^ ERROR: the size for values of type `(dyn Fn() + 'static)` cannot be known at compilation time
5+
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0277]: the size for values of type `(dyn Fn() + 'static)` cannot be known at compilation time
2+
--> $DIR/dont-suggest-impl-as-closure-arg.rs:3:17
3+
|
4+
LL | let c = |f: dyn Fn()| f();
5+
| ^^^^^^^^ doesn't have a size known at compile-time
6+
|
7+
= help: the trait `Sized` is not implemented for `(dyn Fn() + 'static)`
8+
= help: unsized fn params are gated as an unstable feature
9+
help: function arguments must have a statically known size, borrowed types always have a known size
10+
|
11+
LL | let c = |f: &dyn Fn()| f();
12+
| +
13+
14+
error: aborting due to 1 previous error
15+
16+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)