No compiler warning when convert implicitly

Hey everyone,
I have a question about converting a variable implicitly.

When I do this

fn main() {
    let a : u8 = 15;
    let b : u16 = 256;
    println!("a + b = {}", a + (b as u8));
}

I would expect an warning, that there could be problems, cause I convert an u16 to an u8. Why doesn't the compiler warn the user here?

Thanks.

Arguably, writing b as u8 is an explicit conversion.

Nonetheless, the fact that it's a lossy conversion might be surprising, especially because other cases where as conversions are still necessary / useful are non-lossy. There's definitely ongoing discussion at to how to improve / (partially) depreciate certain as-conversions, see e. g. this recent thread in the internals forum: Let's deprecate `as` for lossy numeric casts - Rust Internals.

3 Likes

Oh sorry, I confused implicit and explicit :see_no_evil:

Thanks for your answer, I did not know, that there is an discussion about this already.

1 Like

Clippy actually has a lint for exactly this, it's just allowed by default.

1 Like

Why should it warn you? The as cast is intended to be used when the truncating (or extending, in case of a wider type) behaviour is exactly what you want. It is quite common in low-level algorithms.

If you don't intend to truncate the value and want a lossless conversion, then you shouldn't be using as-casts in the first place. Use From::from for lossless conversions (e.g. u8 -> u16), and TryFrom::try_from for potentially lossy ones (e.g. u16 -> u8, but where you are sure that the value fits in u8).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.