Skip to content

Instantly share code, notes, and snippets.

@ivan3bx
Created May 6, 2016 18:20
Show Gist options
  • Save ivan3bx/23a2b5d15ea3f65ebd63df8effcddf39 to your computer and use it in GitHub Desktop.
Save ivan3bx/23a2b5d15ea3f65ebd63df8effcddf39 to your computer and use it in GitHub Desktop.
Using type alias in custom JSON marshalling
package main
import (
"encoding/json"
"fmt"
"os"
)
type Foo struct {
One string
Two string
// Three is One + Two
}
func (f *Foo) MarshalJSON() ([]byte, error) {
// Alias the original Foo Type to avoid
// recursing through this MarshalJSON func
// further down
type ShadowFoo Foo
return json.Marshal(&struct {
Three string
*ShadowFoo // Use the alias
}{
// Feed data into the anonymosu struct above
Three: fmt.Sprintf("%s + %s", f.One, f.Two), // synthesized data
// Without casting 'f' as the same type declared in
// the anonymous struct, you get the following error:
//
// "cannot use f (type *Foo) as type *ShadowFoo in field value"
//
ShadowFoo: (*ShadowFoo)(f),
})
}
func main() {
data := Foo{One: "1", Two: "2"}
// Output: {"Three":"1 + 2","One":"1","Two":"2"}
_ = json.NewEncoder(os.Stdout).Encode(&data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment