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

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?

1 Like

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://stackoverflow.com/questions/22243527/how-do-you-implement-a-custom-fmtdebug-trait-in-rust
http://rustbyexample.com/hello/print/print_display.html (Similar examples with fmt::Display )

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 Debug in std::fmt - Rust). That seems like an oversight to me.

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

1 Like

That's not an oversight, there're a few obstacles. See
https://github.com/rust-lang/rust/issues/26082
https://github.com/rust-lang/rust/issues/24000
https://github.com/rust-lang/rust/pull/28268
https://github.com/rust-lang/rust/pull/28560

1 Like

I just hit the same problem on rust nightly:

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