Skip to content

Instantly share code, notes, and snippets.

@nikolaydubina
Created March 20, 2024 02:28
Show Gist options
  • Save nikolaydubina/f02d1c52bdec9b9eb28280df61f300cb to your computer and use it in GitHub Desktop.
Save nikolaydubina/f02d1c52bdec9b9eb28280df61f300cb to your computer and use it in GitHub Desktop.
// https://go.dev/play/p/HTKZzENHPcG
package main
import (
"encoding/json"
"fmt"
)
type Color struct{ c uint }
var (
Undefined = Color{}
Red = Color{1}
Green = Color{2}
Blue = Color{3}
)
var colors = map[Color]string{
Red: "red",
Green: "green",
Blue: "blue",
}
var colors_inv = map[string]Color{
"red": Red,
"green": Green,
"blue": Blue,
}
func (s *Color) UnmarshalText(text []byte) error {
s.c = colors_inv[string(text)].c
return nil
}
func (c Color) MarshalText() ([]byte, error) { return []byte(c.String()), nil }
func (c Color) String() string { return colors[c] }
type V struct {
Color Color `json:"color"`
}
func main() {
var v V
s := `{"color": "red"}`
json.Unmarshal([]byte(s), &v)
fmt.Println(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment