Rust

Rust

By DeepSource

Cast from function pointer to non-pointer type RS-W1124

Bug risk

Casting function pointers or closures to integer types other than usize may lead to truncation of the pointer address. If this is the intended behaviour, prefer casting to usize and then casting to the integer type with a comment explaining the reason for the truncation.

Casting function pointers or closures to types that are neither pointers nor integers results in invalid values, introduces bugs or even causing runtime errors in the program.

Consider revisiting the type of this cast.

Bad practice

enum A {
    B(i32)
}

fn add(a: i32, b:i32) -> i32 {
    a + b
}

fn foo() {
    // `A::B` is a constructor(function pointer) and not a value.
    // The pointer to the constructor function
    // itself may not fit in an i32.
    let _ = A::B as i32;
    // `add` is a pointer to the function, which
    // may not fit in an i32 and may be truncated
    let _ = add as i32;
}