Skip to content

Commit d280652

Browse files
committed
Suggest the use of impl Trait in function parameter only
Currently in case of a Trait object in closure parameter, the compiler suggests either to use a reference, which is correct or to use an `impl Trait` which is not. Do not emit this suggestion when the parameter is part of a closure.
1 parent f1bc669 commit d280652

File tree

4 files changed

+31
-6
lines changed

4 files changed

+31
-6
lines changed

compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -3018,12 +3018,16 @@ 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+
if let Some(hir_id) = hir_id
3022+
&& self.tcx.parent_hir_node(hir_id).ident().is_some()
3023+
{
3024+
err.span_suggestion_verbose(
3025+
span,
3026+
"you can use `impl Trait` as the argument type",
3027+
"impl ",
3028+
Applicability::MaybeIncorrect,
3029+
);
3030+
}
30273031
let sugg = if !needs_parens {
30283032
vec![(span.shrink_to_lo(), format!("&{kw}"))]
30293033
} else {

src/tools/tidy/src/issues.txt

+1
Original file line numberDiff line numberDiff line change
@@ -3950,6 +3950,7 @@ ui/traits/issue-104322.rs
39503950
ui/traits/issue-105231.rs
39513951
ui/traits/issue-106072.rs
39523952
ui/traits/issue-117794.rs
3953+
ui/traits/issue-138932.rs
39533954
ui/traits/issue-15155.rs
39543955
ui/traits/issue-18400.rs
39553956
ui/traits/issue-18412.rs

tests/ui/traits/issue-138932.rs

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
fn main() {
2+
let c = |f: dyn Fn()| f();
3+
//~^ ERROR: the size for values of type `(dyn Fn() + 'static)` cannot be known at compilation time
4+
}

tests/ui/traits/issue-138932.stderr

+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/issue-138932.rs:2: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)