Debug (or other) traits for function pointers?


#1

Hi *,

How am i supposed to make function pointers part of enums which needs to have the Debug trait?

Here’s the (simplyfied) example:

#[derive(Debug, Clone)]
enum Obj {
    LIST(Vec<Obj>),
    ATOM(Token),
    NATIVE(NativeFunction),
    NIL
}

type NativeFunction = fn(&Vec<Obj>) -> Obj;

impl fmt::Debug for NativeFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        return write!(f, "here-goes-a-decent-representation");
    }
} // This won't compile ....

I can not go without the Debug trait on Obj but have no idea how to attach a Debug trait on the native-function type in turn. What else could i do?


#2

i guess you have to implement Debug on Obj manual instead of deriving it. Somthing like this

impl fmt::Debug for Obj {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Obj::*;
        match *self {
            LIST(ref v) => v.fmt(f),
            ATOM(ref t) => t.fmt(f),
            NATIVE(_) => write!(f, "here-goes-a-decent-representation"),
            NIL => "NIL".fmt(f),
        }
    }
}

#3

Hi,

thanks for the hint - it did the trick! But this leads to a follow-up question:

Is it possible to get the name of the function a function pointer points to?

Since this is a different question i’ll post this separately.

But anyway - thanks a lot for your help!

cheers, Matthias