Fmt::Debug not implemented for function type with reference argument


#1

I’m trying to use function as struct member and encounter a compile error.
the code is:

#[derive(Debug)]
struct D<T> {
    func : fn(&T)
}

this will give the error:

main.rs:5:5: 5:18 error: the trait core::fmt::Debug is not implemented for the type fn(&T) [E0277]
main.rs:5 func : fn(&T)
^~~~~~~~~~~~~
main.rs:3:10: 3:15 note: in this expansion of #[derive_Debug] (defined in main.rs)
main.rs:5:5: 5:18 help: run rustc --explain E0277 to see a detailed explanation
main.rs:5:5: 5:18 note: fn(&T) cannot be formatted using :?; if it is defined in your crate, add #[derive(Debug)] or manually implement it
main.rs:5:5: 5:18 note: required for the cast to the object type core::fmt::Debug

But strangely, when the argument &T is changed to T, it will compile.

#[derive(Debug)]
struct D<T> {
    func : fn(T)
}                        

And the func member will generate a memory address in {:?}
The version of rustc is 1.6.0.
So Why does function with reference argument does not have a default fmt::Debug implementation?
And how can I solve this problem?


#2

I believe that you have to implement fmt::Debug manually for D. You need something like

impl<T: fmt::Debug> fmt::Debug for D<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // ..... Code here
    }
}

See also


http://rustbyexample.com/hello/print/print_display.html (Similar examples with fmt::Display )


#3

I think the question is more why Debug is implemented for fn(T) extern "C" fn(T), unsafe fn(T) and unsafe extern "C" fn(T) for argument lists of sizes up to 12, but not for functions that borrow their argument (see the huge list here https://doc.rust-lang.org/std/fmt/trait.Debug.html). That seems like an oversight to me.

@doyoubi I would actually recommend opening an issue for that.


#4

That’s not an oversight, there’re a few obstacles. See





#5

I just hit the same problem on rust nightly:
https://is.gd/9qX4Wi

Is this supposed to be solved already? I tried perusing gkoz’ links but I can’t figure it out on my own.