Skip to content

Hint to suggest annotating type to assist unsized coercion #83457

Open
@compiler-errors

Description

@compiler-errors

It would be useful if we could suggest for users to add type annotations to assist in places where the compiler is unable to automagically infer an unsized coersion, e.g. when declaration is separated from usage by a let statement like this code (playground link):

struct Wrapper<T>(T);

fn takes_any(x: Wrapper<Box<dyn std::any::Any>>) {}

fn test() {
    let x = Wrapper(Box::new(1i32));
    takes_any(x);
}

The current output is:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/lib.rs:9:15
  |
9 |     takes_any(x);
  |               ^ expected trait object `dyn Any`, found `i32`
  |
  = note: expected struct `Wrapper<Box<(dyn Any + 'static)>>`
             found struct `Wrapper<Box<i32>>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

Ideally the output should also suggest adding an explicit type annotation to assist in unsizing, like:

 --> src/lib.rs:8:11
  |
8 |    let x: Wrapper<Box<dyn Any>> = Wrapper(Box::new(1i32));
  |           ^^^^^^^^^^^^^^^^^^^^^
help: Annotate the type when the value is created

This error can show up when users are refactoring their code to make lines shorter or more readable, and they might otherwise be confused why an innocuous change can lead to a pretty esoteric compiler error that doesn't suggest a clear fix. Unsure what the best "help" message should be, though!

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-papercutDiagnostics: An error or lint that needs small tweaks.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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