Puzzle 3: Explanation
Explore Rust's type conversion mechanisms, focusing on the lossy nature of the as keyword and how to use safer methods such as Into and TryInto traits. Understand when data loss can occur, how to avoid it, and how to leverage tools like Clippy to detect type conversion issues.
Test it out
Hit “Run” to see the code’s output.
Explanation
The Rust keyword as is lossy, meaning unnecessary information gets discarded. When we use as to convert between types, we run the risk of losing data without warning.
In this example, y is assigned the value 4_294_967_296, but the result is truncated because the number is greater than the maximum value of a 32-bit unsigned integer. It’s surprising that neither the Rust compiler, Clippy, nor the runtime generates any warning or error that data loss has occurred.
If we want to use the as keyword to convert between types, let’s keep the following points in mind:
Here’s a list of some things we need to remember while converting between types that are referenced in the illustration:
-
Converting a smaller type into a larger type (for example,
u32tou64) cannot cause a loss of precision. So, that’s safe to do. -
When working with numbers that are guaranteed to fit in both types, we won’t lose any data. However, we must be careful with user-submitted data or the results of calculations. If we don’t control the data, we can’t be certain that the data will ...