Max Alexander
Max Alexander

Reputation: 5581

How do I implement Debug for a struct containing a function type alias?

I have the following type:

type RangeFn = fn(&Value, &Value) -> bool;

Now I want to put it with this struct:

#[derive(Debug)]
struct Range {
    fun: RangeFn,
}

But if I have a struct that takes RangeFn as a parameter, then I can't seem to have it derive from Debug. How do I make RangeFn compatible with the Debug trait?

Upvotes: 6

Views: 1492

Answers (1)

mcarton
mcarton

Reputation: 30061

You can't implement (or derive) a trait you don't own on a type you don't own.

However, that's not what you want to do. What you want is to implement Debug for Range, but you can't do that by deriving because fns don't implement Debug. Indeed, deriving Debug requires all fields to be Debug as well. Then you are stuck with implementing Debug by yourself; It is after all, just a normal trait:

type RangeFn = fn(&(), &()) -> bool;

struct Range {
    fun: RangeFn,
    other_field: u32,
}

impl std::fmt::Debug for Range {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
        f.debug_struct("Range")
            .field("other_field", &self.other_field)
            .finish_non_exhaustive()
    }
}

fn main() {
    let r = Range {
        fun: |_, _| true,
        other_field: 42,
    };

    println!("{:?}", r);
}

(link to playground)

Upvotes: 11

Related Questions