How it works...

In this recipe, we have two functions, accuracy and percentage, which take in arguments from the main function and convert the type passed to the desired type, due to the nature of the arithmetic operations for which we use the as keywords in Rust which helps in type casting in Rust. In the case of the accuracy function, it takes three input arguments of type i32 and returns a single f32 type value.

In order to protect developers from accidental casts, Rust makes it mandatory for developers to convert data types manually. In the following example, we define an int variable named a and assign it the value 3; after the assignment operation, we would see that a part of the code is commented. This implies that it won't be compiled by the Rust compiler. If we take a careful look at the code, we find that we are multiplying an int variable with a flat value, which will give us a type mismatch error during compilation:

        let a = 3;
/*
let b = a * 0.2; //Won't compile
*/

As we can see, we used the as keyword converting int to float (64-bit) in order to multiply an int value by a float variable. This step produced b without any error:

        let b = a as f64 * 0.2;
Note that when we perform arithmetic operations in the same kind of data type, we don't have to worry about type conversion as the result of the operation produced is automatically typecasted.
..................Content has been hidden....................

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