Skip to content

Wrong help message for Vec::resize_with calls that constrain the Vec to a wrong type #116155

Closed
@narpfel

Description

@narpfel

Code

struct S { xs: Vec<usize> }

fn main() {
    let mut xs = Vec::new();
    xs.resize_with(42, || true);
    S { xs };
}

Current output

error[E0308]: mismatched types
 --> <source>:6:9
  |
5 |     xs.resize_with(42, || true);
  |     --                 ------- this argument has type `[closure@<source>:5:24: 5:26]`...
  |     |
  |     ... which causes `xs` to have type `Vec<bool>`
6 |     S { xs };
  |         ^^ expected `Vec<usize>`, found `Vec<bool>`
  |
  = note: expected struct `Vec<usize>`
             found struct `Vec<bool>`
help: use parentheses to call this closure
  |
5 |     xs.resize_with(42, (|| true)());
  |                        +       +++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
Compiler returned: 1

Desired output

error[E0308]: mismatched types
 --> <source>:6:9
  |
5 |     xs.resize_with(42, || true);
  |     --                 ------- this argument has type `[closure@<source>:5:24: 5:26]`...
  |     |
  |     ... which causes `xs` to have type `Vec<bool>`
6 |     S { xs };
  |         ^^ expected `Vec<usize>`, found `Vec<bool>`
  |
  = note: expected struct `Vec<usize>`
             found struct `Vec<bool>`
help: this expression should have type `usize`
  |
5 |     xs.resize_with(42, || true);
  |                           ~~~~

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
Compiler returned: 1

Rationale and extra context

The same help message is also shown for function calls and other cases which later lead to type errors, such as returning xs from a function with return type Vec<usize>.

Present in 1.72.0 stable and nightly-2023-09-24:

$ rustc -vV
rustc 1.74.0-nightly (37390d656 2023-09-24)
binary: rustc
commit-hash: 37390d65636dd67e263753a3c04fbc60dcc4348e
commit-date: 2023-09-24
host: x86_64-unknown-linux-gnu
release: 1.74.0-nightly
LLVM version: 17.0.0

Other cases

No response

Anything else?

Godbolt link

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-invalid-suggestionDiagnostics: A structured suggestion resulting in 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