RS.CLIPPY.CAST_POSSIBLE_TRUNCATION

Casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: cast_possible_truncation. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for casts between numeric types that may truncate large values. This is expected behavior, so the cast is Allow by default. It suggests user either explicitly ignore the lint, or use try_from() and handle the truncation, default, or panic explicitly.

Why is this bad?

In some problem domains, it is good practice to avoid truncation. This lint can be activated to help assess where additional checks could be beneficial.

Example

fn as_u8(x: u64) -> u8 {
    x as u8
}

Use instead:

fn as_u8(x: u64) -> u8 {
    if let Ok(x) = u8::try_from(x) {
        x
    } else {
        todo!();
    }
}
// Or
#[allow(clippy::cast_possible_truncation)]
fn as_u16(x: u64) -> u16 {
    x as u16
}