liveBook · Manning

TextMarshaler

As explained in Go by Example

TextMarshaler is a Go interface for types that can encode themselves as text.

TextMarshaler is the encoding.TextMarshaler interface for values that encode themselves as text through MarshalText() ([]byte, error). Standard-library consumers can recognize this shared behavior without depending on a concrete type. section 10.4.1

A type can implement TextMarshaler independently of how its encoded form will be used. For example, net.IP supplies MarshalText, allowing encoding/json to serialize an IP field as a quoted address. section 10.4.1

Use TextMarshaler when:

  • A flag value needs custom text encoding alongside TextUnmarshaler decoding. section 4.3.2
  • Several consumers need the same text-encoding behavior and a shared interface has emerged from concrete use. section 10.4.1
  • A standard consumer such as json.Marshal should serialize a custom value through its own MarshalText method. section 10.4.1

Parsing an IP flag

var ip net.IP fs.TextVar(&ip, "ip", &ip, "`IP` address") fs.Parse([]string{"-ip", "10.0.0.1"}) fmt.Println(ip.IsPrivate()) TextVar uses the value's TextMarshaler and TextUnmarshaler implementations; net.IP therefore participates directly in flag parsing and validation. section 4.3.2

JSON serialization

type Server struct { Addr net.IP `json:"addr"` } data, err := json.Marshal(Server{Addr: net.IPv4(192, 168, 1, 1)}) fmt.Println(string(data)) The resulting address field is encoded as {"addr":"192.168.1.1"}. section 10.4.1

package encoding
type TextMarshaler interface {
    MarshalText() (text []byte, err error)
}

Inspect the minimal interface definition and its single MarshalText method. section 10.4.1

How Go by Example covers it

How deep it goes
Defines one method and demonstrates standard-library delegation, but does not develop custom MarshalText implementations.
Examples
Uses net.IP in command-line parsing and JSON serialization.
What you can do after
Apply it via flag.FlagSet.TextVar and json.Marshal when a type exposes a text representation.
How it connects
Connects TextUnmarshaler, flag.FlagSet.TextVar, net.IP, encoding/json, and consumer-side interface design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.