Joyal Mathew
Joyal Mathew

Reputation: 624

How to compare a function stored in a struct to what it's referencing

Is there any way to compare bar.foo to foo?

fn foo() {

}

struct Bar {
    foo: &'static (dyn Fn()),
}

fn main() {
    let bar = Bar { foo: &foo };

    if bar.foo == foo {
        println!("equal");
    }
}

(Playground)

This gives the error: binary operation `==` cannot be applied to type `&dyn std::ops::Fn()

This question cannot be applied to my case. It proposes trying to check the return value or cast the functions to a usize. foo doesn't return anything and bar.foo cannot be cast to a usize.

Upvotes: 1

Views: 140

Answers (1)

jplatte
jplatte

Reputation: 1141

You can test function pointer equality by first converting the references to raw pointers: bar.foo as *const _ == &foo as *const _.

Note however that this is not very robust. There's a high chance you'll run into a situation where you would expect the pointers to be equal, but they aren't. To quote eddyb from a reddit post that asked the same thing:

Note that there are no guarantees about getting the same function pointer twice - you'd need to be within the same crate and codegen unit, when casting the function to a pointer, to have a chance.

Oh and LLVM will happily combine two different functions into one, if they happen to have identical bodies, so watch out for that too.

Upvotes: 5

Related Questions