Display function pointer


#1

I wrote this to display two vectors:

fn show(a: fn () -> f32, b: fn (&Vec<i8>)->f32) {
    println!("the two pointers: {:p} {:p}", a, b);
}

At compilation, there is no probleme to understand that ‘a’ is displayed,but rust says that the std::fmt::Pointer trait is not implemented for type fn (&Vec)->f32

Why that ?
How can we display function pointer addresses in Rust ?


Why does not a function generic over a lifetime implement Debug?
#2

I would cast to usize:

fn show(a: fn () -> f32, b: fn(&Vec<i8>) -> f32) {
    println!("the two pointers: {:p} {:x}", a, b as usize);
}

Note that I edited your post for formatting, check it out!


#3

This looks like a bug (or perhaps a limitation) to me. Namely, HRTB fn pointers don’t have std::fmt::Pointer implemented. A couple of workarounds to use {:p} formatting:

// add a generic lifetime param to `show` and bind that to the `Vec` reference
fn show<'a>(a: fn() -> f32, b: fn(&'a Vec<f32>) -> f32) {
    println!("the two pointers: {:p} {:p}", a, b);
}
// coerce to a non-HRTB fn 
fn show(a: fn() -> f32, b: fn(&Vec<f32>) -> f32) {
    let erased: fn(&'static Vec<f32>) -> f32 = b;
    println!("the two pointers: {:p} {:p}", a, erased);
}

You can also cast to usize like @steveklabnik showed and switch {:x}.


#4

Thanks a lot ! I hope this bug or limitation will be solved out (if it’s possible) cause the necessity to cast the function pointer to display it whereas that’s not needed for other pointer types is not intuitive.


#5

It’s not all fn pointers that need this - just ones with an HRTB bound on its reference parameter(s).

@steveklabnik do you think this is a bug/omission? If so, maybe we should file an issue.


#6

It certainly feels not great to me; I’m not sure. Probably worth filing a bug.


#7

I don’t understand why certain functions pointers can be displayed and other not … The signatures are not the same OK and some have non-static arguments, but it’s always pointers isn’t it ?


#8

The HRTB variants are missing a std::fmt::Pointer impl.

Can you please file a github issue and paste the link here?


#9

sure: it’s now there https://github.com/rust-lang/rust/issues/50280