pub fn fn_addr_eq<T, U>(f: T, g: U) -> bool
ptr_fn_addr_eq
#129322)Expand description
Compares the addresses of the two function pointers for equality.
This is the same as f == g
, but using this function makes clear that the potentially
surprising semantics of function pointer comparison are involved.
There are very few guarantees about how functions are compiled and they have no intrinsic “identity”; in particular, this comparison:
-
May return
true
unexpectedly, in cases where functions are equivalent.For example, the following program is likely (but not guaranteed) to print
(true, true)
when compiled with optimization: -
May return
false
in any case.This is particularly likely with generic functions but may happen with any function. (From an implementation perspective, this is possible because functions may sometimes be processed more than once by the compiler, resulting in duplicate machine code.)
Despite these false positives and false negatives, this comparison can still be useful. Specifically, if
T
is the same type asU
,T
is a subtype ofU
, orU
is a subtype ofT
, andptr::fn_addr_eq(f, g)
returns true,
then calling f
and calling g
will be equivalent.