Skip to content

Suggest parse on expected types that implement FromStr #159494

Description

@estebank

Code

fn main() {
    let port: u16 = "8080";
    println!("{port}");
    let text = String::from("42");
    let number = text as i32;
}

Current output

error[E0308]: mismatched types
  --> $DIR/string-literal-assigned-to-parsable-type.rs:11:21
   |
LL |     let port: u16 = "8080";
   |               ---   ^^^^^^ expected `u16`, found `&str`
   |               |
   |               expected due to this

error[E0605]: non-primitive cast: `String` as `i32`
  --> $DIR/string-to-number-with-as.rs:10:18
   |
LL |     let number = text as i32;
   |                  ^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object

Desired output

Suggest `"8080".parse<i16>().unwrap()` and `let number = text.parse::<i32>().unwrap()`.

For the former, detect literal could have been a number to begin with.

Rationale and extra context

No response

Other cases

Rust Version

1.97

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-lack-of-suggestionDiagnostics: Adding a (structured) suggestion would increase the quality of the diagnostic.D-papercutDiagnostics: An error or lint that needs small tweaks.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