Interfaces · 3 MIN READ

fmt looks for String(), not a Stringer keyword

Make a type print itself as a dotted IPv4 address.

fmt.Stringer is a small formatting contract:

go
type Stringer interface { String() string }

Common string formatting operations in fmt call String() when the value implements it. Format verbs that explicitly request another representation may behave differently. No registration is needed.

Do not format the same value through its own String method in a way that calls String again. Convert it to its underlying type or format its fields to avoid recursion.

SEE THE IDEA

Formatting can ask the value how to display itself

  1. 01

    Your type

    go
    type Label int

    Carries application meaning

  2. 02

    Method

    go
    String() string

    Returns a readable representation

  3. 03

    Formatting

    go
    fmt.Sprint(label)

    Uses the Stringer contract where applicable

String returns text; it does not print or change the value.

In practice

Keep String useful for logs and human-facing diagnostics. Some format verbs request a numeric or other specific representation, so not every fmt operation uses String. Separate machine serialization from String when a stable wire format is required.

Watch out

Formatting the same value with a string verb from inside its own String method can recurse. Convert to the underlying type first.

Official reference ↗

Work through the exercise

go
package main

type IPAddr [4]byte

// String should print 1.2.3.4 for IPAddr{1, 2, 3, 4}.
func (ip IPAddr) String() string {
	return ""
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.