diff options
Diffstat (limited to 'playground/main.go')
-rw-r--r-- | playground/main.go | 34 |
1 files changed, 31 insertions, 3 deletions
diff --git a/playground/main.go b/playground/main.go index 38b5f0d..8c67cc0 100644 --- a/playground/main.go +++ b/playground/main.go @@ -8,9 +8,35 @@ import ( "os" ) +type Optional[T any] struct { + Value T + Exists bool +} + +func (o *Optional[T]) UnmarshalJSON(data []byte) error { + var Temp *T + + err := json.Unmarshal(data, &Temp) + if err != nil { + return err + } + + if Temp == nil { + var empty T + o.Value = empty + o.Exists = false + return nil + } + + o.Value = *Temp + o.Exists = true + return nil +} + type Testy struct { - Flag *bool `json:"flag"` - Cake *[]string `json:"cake"` + Flag *bool `json:"flag"` + Cake *[]string `json:"cake"` + Opt Optional[string] `json:"opt"` } const TEXT = `{ @@ -18,11 +44,13 @@ const TEXT = `{ "one", "two", "three" - ] + ], + "opt": "peter" }` const TEMPLATE = `Flag is: {{if .Flag}}{{.Flag}}{{else}}[none]{{end}} Cake is: {{if .Cake}}{{range .Cake}}{{.}} {{end}}{{else}}[none]{{end}} +Opt is: {{if .Opt.Exists}}{{.Opt.Value}}{{else}}[none]{{end}} ` func main() { |