Skip to content

Instantly share code, notes, and snippets.

@cwinters
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwinters/b5fa13ba07b51e0e83c8 to your computer and use it in GitHub Desktop.
Save cwinters/b5fa13ba07b51e0e83c8 to your computer and use it in GitHub Desktop.
// run with: go run embedded_structs.go
package main
import (
"encoding/json"
"fmt"
)
type ProductFields struct {
ID uint `json:"id"`
Name string `json:"name"`
CurrentPrice string `json:"current_price"`
IsOnSale bool `json:"is_on_sale"`
}
type Product struct {
ID uint `json:"id"`
ProductFields
}
type Variant struct {
ID uint `json:"id"`
VariantDescription string `json:"variant"`
ProductFields
}
func jsonDump(label string, thingy interface{}) []byte {
serialized, _ := json.Marshal(thingy)
fmt.Printf(label+" as JSON:\n %s\n", serialized)
return serialized
}
func main() {
fields := ProductFields{
ID: 9876,
Name: "Grabthar's Hammer",
CurrentPrice: "59.99",
IsOnSale: false,
}
jsonDump("Product fields", fields)
p := Product{
ID: 123,
ProductFields: fields,
}
jsonDump("Product", p)
v := Variant{
ID: 8181,
VariantDescription: "Size: Large / Color: Mauve",
ProductFields: fields,
}
variantJson := jsonDump("Variant", v)
newVariant := Variant{}
json.Unmarshal(variantJson, &newVariant)
fmt.Printf("Variant serialized from JSON\n [ID: %d] [Name: %s] [Price: %s] [On sale? %t] [Variant: %s]\n",
newVariant.ID, newVariant.Name, newVariant.CurrentPrice, newVariant.IsOnSale, newVariant.VariantDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment