Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

diagnostics: suggest using smaller type if constant is small enough and smaller type impls conversion #53266

Open
matthiaskrgr opened this issue Aug 11, 2018 · 2 comments
Labels
A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@matthiaskrgr
Copy link
Member

this code

fn main() {
    let x = 123.1234_f32 - f32::from(100);
}

fails to compile as follows:

error[E0277]: the trait bound `f32: std::convert::From<i32>` is not satisfied
 --> src/main.rs:2:28
  |
2 |     let x = 123.1234_f32 - f32::from(100);
  |                            ^^^^^^^^^ the trait `std::convert::From<i32>` is not implemented for `f32`
  |
  = help: the following implementations were found:
            <f32 as std::convert::From<u8>>
            <f32 as std::convert::From<i16>>
            <f32 as std::convert::From<u16>>
            <f32 as std::convert::From<i8>>
  = note: required by `std::convert::From::from
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.

We know that 100 < <u8>::max_value()and that there is <f32 as std::convert::From<u8>> thus maybe we could suggest using f32::from(100_u8) instead?

@leonardo-m
Copy link

thus maybe we could suggest using f32::from(100_u8) instead?

Even better is to see 100 as a untyped value that can fit into the <f32 as std::convert::From<u16>>. So the _u8 is unnecessary. Is this possible?

@matthiaskrgr
Copy link
Member Author

Hmm, on second thought, it might be confusing if

let y = f32::from(100);

behaves differently from

let x = 100; // i32
let y = f32::from(x);

so forcing to explicitly make it u8 might be more clear.

@estebank estebank added the A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. label Jan 11, 2019
@JohnTitor JohnTitor added C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Oct 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-suggestion-diagnostics Area: Suggestions generated by the compiler applied by `cargo fix`. C-enhancement Category: An issue proposing an enhancement or a PR with one. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

4 participants