Skip to content

Papercut: Suggest Default::default() when binding isn't initialized #102087

Closed
@Patryk27

Description

@Patryk27

Given the following code:

fn main() {
    let foo: Vec<&str>;
    
    foo.push("hi!");
}

(playground link)

... the current output is:

error[E0381]: used binding `foo` isn't initialized
 --> src/main.rs:4:5
  |
2 |     let foo: Vec<&str>;
  |         --- binding declared here but left uninitialized
3 |     
4 |     foo.push("hi!");
  |     ^^^^^^^^^^^^^^^ `foo` used here but it isn't initialized

While this message is correct, people (especially beginners) stumbling upon it sometimes still don't know what to do (e.g. they expect let var: ty; to automatically initialize var to Default::default(), as is the case in some languages).

Maybe we could extend the message to say:

error[E0381]: used binding `foo` isn't initialized
 --> src/main.rs:4:5
  |
2 |     let foo: Vec<&str>;
  |         --- binding declared here but left uninitialized
3 |     
4 |     foo.push("hi!");
  |     ^^^^^^^^^^^^^^^ `foo` used here but it isn't initialized
  |
help: use `=` to assign some value to `foo`
  |
2 |     let foo: Vec<&str> = something;
  |                          ~~~~~~~~~

... with an extra case that if ty is Default:

help: use `=` to assign default value to `foo`
  |
2 |     let foo: Vec<&str> = Default::default();
  |                          ~~~~~~~~~~~~~~~~~~

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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