Skip to content

Suboptimal error reporting of invalid argument to generic function #36775

Closed
@Seeker14491

Description

@Seeker14491

The following code produces two compilation errors.

use std::fmt::Display;

fn main() {
    let _ = Vec::with_capacity("0"); // error #1

    displayer(()); // error #2
}

fn displayer<T: Display>(t: T) {
    println!("{}", t);
}

Error 1

error[E0308]: mismatched types
 --> <anon>:4:32
  |
4 |     let _ = Vec::with_capacity("0"); // error #1
  |                                ^^^ expected usize, found reference
  |
  = note: expected type `usize`
  = note:    found type `&'static str`

The first error looks great. The compiler points at the erroneous argument.

Error 2

error[E0277]: the trait bound `(): std::fmt::Display` is not satisfied
 --> <anon>:6:5
  |
6 |     displayer(()); // error #2
  |     ^^^^^^^^^ trait `(): std::fmt::Display` not satisfied
  |
  = note: `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
  = note: required by `displayer`

In the second error, however, the compiler points at the function instead of the erroneous argument. This is no big problem in this case, as the function only takes one argument, and the argument has a very simple type. But in more complex functions, it might be hard to figure out which argument is problematic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.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