Created
May 6, 2016 18:20
-
-
Save ivan3bx/23a2b5d15ea3f65ebd63df8effcddf39 to your computer and use it in GitHub Desktop.
Using type alias in custom JSON marshalling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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