Reference to different functions pointing to the same address?

While working with function pointer/reference for my embedded Rust project, I found reference to different functions are generating the same address (&foo and &bar), while actual function addresses are certainly different.

This itself was not a blocker for my project, but I'm interested in knowing what is happening behind this. Can anyone enlighten me what Rust is doing here?

It would have made sense for me if reference to a function resulted to the same address of the function itself (C-ism), or each reference to a function resulted to different addresses that represents something additionally allocated. Having the same address between different references is puzzling me.

fn foo() { println!("foo"); }
fn bar() { println!("bar"); }

fn main() {
    let val1 = 100;
    let val2 = 200;
    println!("&val1={:p}", &val1);
    println!("&val2={:p}", &val2);
    
    println!("foo={:p}, &foo={:p}", foo as fn(), &foo);
    println!("bar={:p}, &bar={:p}", bar as fn(), &bar);
}


(Playground)

Output:

&val1=0x7ffec48b53a0
&val2=0x7ffec48b53a4
foo=0x5631d26e5a20, &foo=0x5631d2706d24
bar=0x5631d26e5a60, &bar=0x5631d2706d24

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.44s
     Running `target/debug/playground`

Note that &foo is a reference to a value of a zero-sized type called a function item, so it can tell the difference between them using type information. Please see this playground

fn main() {
    let val1 = 100;
    let val2 = 200;
    println!("&val1={:p}", &val1);
    println!("&val2={:p}", &val2);
    
    println!("foo={:p}, &foo={:p}", foo as fn(), &foo);
    println!("bar={:p}, &bar={:p}", bar as fn(), &bar);
    println!("bar={:p}, &bar={:p}", foo as fn(), &());
}

where the last &() which is a reference to some other kind of zero-sized type also has the same address as the other two. (It's a reference into the compiled binary, which you can see by comparing it to a &"text", which has a similar address.)

2 Likes

Thank you for enlightment! Type-based tricks in Rust is certainly interesting.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.