如何将存储在结构中的函数与其引用的函数进行比较

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

有什么方法可以比较 bar.foofoo 吗?

fn foo() {

}

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

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

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

(Playground)

这给出了错误:binary operation `==` cannot be applied to type `&dyn std::ops::Fn()

不适用于我的情况。它建议尝试检查 return 值或将函数转换为 usizefoo 没有 return 任何东西并且 bar.foo 不能转换为 usize.

您可以通过首先将引用转换为原始指针来测试函数指针相等性:bar.foo as *const _ == &foo as *const _

但是请注意,这不是很可靠。您很有可能会 运行 遇到您希望指针相等的情况,但实际上并非如此。引用 reddit post that asked the same thing 中的 eddyb:

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.