I have a function that encodes Go data structure in a certain way. Below is 
a an example
// Data structure
type DataX struct{
   X string `query:"x"`
}

func MarshalJSON(v interface)([]byte, error){
   s := query.Encode(v)
   return s.Bytes(), nil
}

Currently in order to force the json encoder use this function on `type 
DataX` I have to implement json.Marshaler on it and call the same 
MarshalJSON function. 
e.g. 
func(x *DataX)MarshalJSON()([]byte, error){
   // use our "generic"/common function
   return MarshalJSON(v)
}

Is there is generic way to reduce this boilerplate ? Why do I have to write 
a method if I know that all it does it to call the same function? I 
thinking about something like this:

// Define DataX as a struct that also implements QueryMarshaler??
// unicorn code.
type DataX struct [QueryMarshaler]{
   X string `query:"name"`
}
// DataY implments  QueryMarshaler's methods as well
type DataY  [QueryMarshaler]{
  Y string `query:"y"`
}
///...

// QueryMarshaler method 
type QueryMarshaler interface{}

func [K QueryMarshaler](v K)MarshalJSON()([]byte, error){
   s := query.Encode(v)
   return s.Bytes(), nil
}


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/4cf4f8da-5866-4a32-8624-6ffb9740ed18n%40googlegroups.com.

Reply via email to