Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 861
Max Alexander Avatar asked Jan 02 '23 22:01

Max Alexander


1 Answers

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()
    }
}

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

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

(link to playground)

like image 135
mcarton Avatar answered Jan 04 '23 22:01

mcarton