Skip to content

Invalid suggestion to add dyn to something that is not a trait #139174

Closed
@pacak

Description

@pacak

Code

fn derp<'a>(x: Box<dyn Fn() -> Option<usize + 'a>>) -> usize {
    x()
}

Current output

Checking foo v0.1.0 (/home/pacak/tmp/foo)
error[E0404]: expected trait, found builtin type `usize`
 --> src/lib.rs:1:39
  |
1 | fn derp<'a>(x: Box<dyn Fn() -> Option<usize + 'a>>) -> usize {
  |                                       ^^^^^ not a trait

error[E0782]: expected a type, found a trait
 --> src/lib.rs:1:39
  |
1 | fn derp<'a>(x: Box<dyn Fn() -> Option<usize + 'a>>) -> usize {
  |                                       ^^^^^^^^^^
  |
help: you can add the `dyn` keyword if you want a trait object
  |
1 | fn derp<'a>(x: Box<dyn Fn() -> Option<dyn usize + 'a>>) -> usize {
  |                                       +++

Some errors have detailed explanations: E0404, E0782.
For more information about an error, try `rustc --explain E0404`.
error: could not compile `foo` (lib) due to 2 previous errors

Desired output

Not suggesting dyn would be a good start, suggesting to move > to the left would be even better

Rationale and extra context

Let's start with some valid code (lifetime is redundant here, but makes sense in my full code).

fn derp<'a>(x: Box<dyn Fn() -> usize + 'a>) -> usize {
    x(); todo!();
}

And change it to the value produced is Optional:

This works:

fn derp<'a>(x: Box<dyn Fn() -> Optional<usize> + 'a>) -> usize {
    x(); todo!();
}

But imagine making a typo...

fn derp<'a>(x: Box<dyn Fn() -> Optional<usize + 'a>>) -> usize {
    x(); todo!();
}

Error message is confusing and suggestion is wrong.

Other cases

Nightly suggests to add a parameter for a closure that takes no parameters... In addition to suggesting to adding dyn

error[E0057]: this function takes 1 argument but 0 arguments were supplied
 --> src/lib.rs:2:5
  |
2 |     x()
  |     ^-- argument #1 is missing
  |
note: implementation defined here
 --> /rustc/f8c27dfe1a2e7fb538fd91dad53de06992c7c967/library/alloc/src/boxed.rs:1978:1
help: provide the argument
  |
2 |     x(/* value */)
  |       +++++++++++

Rust Version

rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-unknown-linux-gnu
release: 1.85.0
LLVM version: 19.1.7

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutD-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-verboseDiagnostics: Too much output caused by a single piece of incorrect code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions