Create a gist now

Instantly share code, notes, and snippets.

// 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