Found transmute from integer type to floating point typeRS-W1127
In Rust, the transmute function is used to reinterpret the bits of a value of one type as another type. Hence, both types must have the same size.
Compilation will fail if this is not guaranteed. Transmute is semantically equivalent to a bitwise move of one type into another. It copies the bits from the source value into the destination value.
Hence, transmuting from integer type to floating point type is considered bad in Rust because it can lead to invalid in-memory representation and undefined behavior.
For example, bitcasting integer type to float can produce the representation of NaN
which
is otherwise an invalid float type in most arithmetic operations.
Consider using as
cast if you really must cast between the two types and want expected
results, aka rounded floating values.
Bad practice
fn main() {
let x: i32 = 42;
let y: f32 = unsafe { std::mem::transmute(x) };
}
Recommended
fn main() {
let x: i32 = 42;
let y: f32 = x as f32;
}