In Rust, type casting is performed using the as keyword. It explicitly converts one type to another:
let x: i32 = 10; let y: u8 = x as u8;
Rust does not perform implicit casts like C or C++, which prevents many errors related to data loss or overflows.
Features:
Potential dangers:
i32 to u8, if the value goes out of range, excess higher bits are simply discarded — this can lead to unexpected behavior.Example:
let big: u16 = 300; let small: u8 = big as u8; // small == 44, since 300 % 256 = 44
What happens if you cast a negative number of type
i8to typeu8using theaskeyword?
Answer: The value does not cause a compilation error or runtime panic. Instead, the bits of the value are interpreted as an unsigned number:
let x: i8 = -1; let y: u8 = x as u8; // y == 255
Story
In a financial application, data about the sum of transfers were initially stored as i32. The developer decided to convert them to u32 without boundary checking, which led to incorrect handling of negative values — sums unexpectedly became large positive numbers, passing business logic validation!
Story
In a game for microcontrollers, the difference in two level values was used to calculate acceleration changes: the result could be negative. as u8 was used for rounding the result, ignoring overflows. As a result, speeds "stuck" at maximum levels because negative values turned into large positives due to wrap-around behavior.
Story
In a network application, when copying a data buffer, the length was calculated as the difference of pointers (usize), and then cast to u32 using as. With large amounts of memory (>4 GB), this led to value truncation, causing data loss and errors when transmitting large files.