How to do a truncating conversion without triggering `clippy`?

How do I tell clippy that some cast is lossy on purpose (clippy::cast_possible_truncation and some other)? Such as:

f64 as f32
f32.round().clamp(min, max) as i32
i32.clamp(min, max) as f32
u32.clamp_max(max) as i32

Is there an idiomatic way to achieve this without having to disable the clippy rule?

Create a helper function which does the conversion and disable the rule for only this function. I’m not sure if this is idiomatic though, but my first intuition.

1 Like

Lints can be disabled for a single statement or expression:

#[allow(clippy::cast_possible_truncation)]
let truncated = foo as i32;

This also works for functions, loops, etc.

I asked this question because I wanted to avoid to disable the rules in lots of places.
A warning is typically a hint that there’s a better way. Lots of similar problems could be solved with try_from or Wrapping or saturating math.

This partucular lint is of “pedantic” group and allow by default, so perhaps you shouldn’t pay too much attention to it, unless you know that it’ll help you catch some bugs (and in this case you’ll possibly want to deny it for some particular modules and not for the whole crate).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.