Skip to content

Don't suggest 42u8.into(), suggest "change the literal to 42u16 #54160

Closed
@estebank

Description

@estebank

Given the following code

fn foo(_: u16) {}
fn main() {
    foo(8u8);
}

we currently suggest using .into() to turn the u8 literal into a u16

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |     foo(8u8);
  |         ^^^ expected u16, found u8
help: you can cast an `u8` to `u16`, which will zero-extend the source value
  |
3 |     foo(8u8.into());
  |         ^^^^^^^^^^

We should suggest changing the literal directly when appropriate in the following way:

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |     foo(8u8);
  |         ^^^ expected u16, found u8
help: change the type of the numeric literal from `u8` to `u16`
  |
3 |     foo(8u16);
  |         ^^^^

This has the added benefit that we can look at the literal and see if it would also fit when reducing the size (from 16 to 8, for example) if the literal would fit in the smaller type.

The current suggestion is implemented in check_for_cast and would require evaluating the expr to see if it is a literal with an explicit type suffix or not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions