fn_addr_eq in std::ptr - Rust (original) (raw)

Function fn_addr_eq

1.85.0 · Source

pub fn fn_addr_eq<T, U>(f: T, g: U) -> bool

where
    T: FnPtr,
    U: FnPtr,

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:

let f: fn(i32) -> i32 = |x| x;  
let g: fn(i32) -> i32 = |x| x + 0;  // different closure, different body  
let h: fn(u32) -> u32 = |x| x + 0;  // different signature too  
dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); // not guaranteed to be equal  

Despite these false positives and false negatives, this comparison can still be useful. Specifically, if

then calling f and calling g will be equivalent.

§Examples

use std::ptr;

fn a() { println!("a"); }
fn b() { println!("b"); }
assert!(!ptr::fn_addr_eq(a as fn(), b as fn()));