encoding.TextMarshaler / TextUnmarshaler
JSON, XML, YAML, env parsers all check for TextMarshaler. One implementation covers them all.
type Color struct{ R, G, B uint8 }
func (c Color) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)), nil
}
func (c *Color) UnmarshalText(text []byte) error {
_, err := fmt.Sscanf(string(text), "#%02x%02x%02x", &c.R, &c.G, &c.B)
return err
}
b, _ := json.Marshal(Color{255, 0, 128}) // "\"#ff0080\""