Rust

Rust

Made by DeepSource

Comparing function pointer to null RS-W1115

Bug risk
Major

In Rust, function pointers are assumed to not be null. Just like references, it is expected that nullable function pointers are implemented using Option. Hence, checking if they are null is invalid. Instead, the wrapped Option can be compared to None using Option::is_none(..) like <fn_ptr>.is_none() to establish if the pointer is not present.

Bad practice

fn bar() {}
fn foo() {
    let fn_ptr: fn() = bar;
    if (fn_ptr as *const ()).is_null() {
        // ...
    }
}

Recommended

fn bar() {}
fn foo() {
    let fn_ptr: Option<fn()> = bar.into();
    if fn_ptr.is_none() {
        // ...
    }
}