Pointing out trivial casts

Sometimes, we might explicitly cast an element to a type that the compiler should cast automatically. This sometimes happens when we use traits, but it can also happen because we changed the type of an element to a new type and we didn't change the castings. To clean these kinds of behavior, we have the trivial_casts and trivial_numeric_casts lints. Let's see it as an example:

#![warn(trivial_casts, trivial_numeric_casts)]

#[derive(Default, Debug)]
struct MyStruct {
a: i32,
b: i32,
}

fn main() {
let test = MyStruct::default();
println!("{:?}", (test as MyStruct).a as i32);
}

In this case, we first cast test as a MyStruct, but it's already a MyStruct, so this is redundant and makes the code much less readable, and in consequence, more error-prone. Then we cast its a attribute as an i32, but it's already an i32, so once again, redundant information. The first is not common, but the second could be found if we use this parameter for a function that only accepts an i32, and our structure had i16 in a previous implementation, for example.

In any case, these kinds of castings are not good practice, since it could be that we had changed the a attribute for an i64, and we would be silently losing precision. We should use i32::from() so that if we change it for an i64, it will simply stop compiling. This gets automatically linted with the Clippy tool we will see later.

It is a good idea to enable these two lints anyway, since it will help us find these kinds of errors. The trivial_casts lint will lint us for non-numeric type/trait casts, while trivial_numeric_casts will lint the numeric casts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.221.133