ProgrammingEmbedded Developer / Systems Developer

How does type casting work in Rust? What are the features and potential dangers of using casting between numeric types?

Pass interviews with Hintsage AI assistant

Answer

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:

  • Conversion between numeric types is only possible explicitly.
  • When casting from one numeric type to another, overflows and loss of significant bits may occur.
  • Application to pointers and values compatible in size is allowed but requires caution.

Potential dangers:

  • When casting for example from i32 to u8, if the value goes out of range, excess higher bits are simply discarded — this can lead to unexpected behavior.
  • Explicit conversion does not cause panic or a runtime error!

Example:

let big: u16 = 300; let small: u8 = big as u8; // small == 44, since 300 % 256 = 44

Trick Question

What happens if you cast a negative number of type i8 to type u8 using the as keyword?

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

Examples of real errors due to ignorance of the nuances of the topic.


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.