Created
March 20, 2024 02:28
-
-
Save nikolaydubina/f02d1c52bdec9b9eb28280df61f300cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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