Skip to content

Suggest converting a type to trait object when it's possible and the method expects one #42499

Open
@golddranks

Description

@golddranks

If the method explicitly expects a trait object, such as &postgres::types::ToSql, (ToSql is a trait), and the user is trying to pass it a type that implements the trait, such as String, it's likely that the user either doesn't understand the distinction between trait object and trait bounds in generics, or has accidentally missed that the function isn't expecting a generic type but a trait object.

In this case, it would be helpful to show a more specific error message than the standard "type mismatch". The standard error message is like this:

error[E0308]: mismatched types
  --> src/main.rs:75:39
   |
75 |     for row in &conn.query(get_table, schemas.as_slice()).unwrap() {
   |                                       ^^^^^^^^^^^^^^^^^^ expected trait postgres::types::ToSql, found struct `std::string::String`
   |
   = note: expected type `&[&postgres::types::ToSql]`
              found type `&[&std::string::String]`

First of all, "expected trait" is downright misleading, I think it should be "expected trait object". Secondly, it would be helpful to show a hint that says that:

  1. String implements trait ToSql, but this method is expecting a trait object, not any type that implements the trait.
  2. You can create a trait object from a value of type &String with value as &postgres::types::ToSql.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.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