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
