Skip to content

Instantly share code, notes, and snippets.

@dpetersen
Last active August 29, 2015 14:16
Show Gist options
  • Save dpetersen/b68669c256935217c4ba to your computer and use it in GitHub Desktop.
Save dpetersen/b68669c256935217c4ba to your computer and use it in GitHub Desktop.
Serialize shmerialize
package main
import (
"encoding/json"
"fmt"
)
type Cat struct {
Angry bool `json:"angry"`
Declawed bool `json:"declawed"`
}
type CatThreatAssessment struct {
Cat
IsDangerous bool `json:"is_dangerous"`
}
func NewCatThreatAssessment(c Cat) CatThreatAssessment {
return CatThreatAssessment{
Cat: c,
IsDangerous: c.Angry && !c.Declawed,
}
}
func main() {
dangerousCat := Cat{Angry: true, Declawed: false}
justAngryCat := Cat{Angry: true, Declawed: true}
dcj, _ := json.MarshalIndent(NewCatThreatAssessment(dangerousCat), "", " ")
jacj, _ := json.MarshalIndent(NewCatThreatAssessment(justAngryCat), "", " ")
fmt.Printf("dangerousCat JSON:\n%v\n", string(dcj))
fmt.Printf("justAngryCat JSON:\n%v\n", string(jacj))
}
@dpetersen
Copy link
Author

Output:

dangerousCat JSON:
{
  "angry": true,
  "declawed": false,
  "is_dangerous": true
}
justAngryCat JSON:
{
  "angry": true,
  "declawed": true,
  "is_dangerous": false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment