encoding

Guided tour · Encoding · pkg.go.dev →

The shared interfaces every encoding package honors: BinaryMarshaler, TextMarshaler, and their Unmarshaler pairs.

The four interfaces

Implement these once and your type slots into many encoders.

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\""

encoding.BinaryMarshaler / BinaryUnmarshaler

Used by encoding/gob and some caches. Less common — reach for it when you need compact on-disk or on-wire formats.