Skip to main content
Module 6 · Lesson 4 of 529/50 in the course~10 min
Module lessons (4/5)

The Stringer interface

Lesson preview5 hands-on exercises readyCourse Go · Module 6 — Interfaces

Implementing String() string changes how fmt.Println represents your type.

What you'll learn in this lesson

  • Implement fmt.Stringer (String() string) to customize text rendering in logs, fmt.Println, and debug messages.
  • Apply Stringer to enumerations based on iota to print readable labels instead of raw numbers.
  • Avoid infinite recursions inside String() and understand why the value receiver is almost always convenient.

Overview

In the fmt package, the most used interface after error is fmt.Stringer:

Each time you pass a value to fmt.Println, fmt.Printf("%v", x), or fmt.Sprintf, fmt internally checks whether the value implements fmt.Stringer and invokes String().

Sections covered in this lesson

  1. 1Enums with iota made readable
  2. 2Avoid infinite recursion in String()
  3. 3Why use a value receiver on String()
  4. 4Custom formatting for fmt.GoStringer (%#v)
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 6 — Interfaces

Unlock "The Stringer interface" and the full Course Go curriculum

Implementing `String() string` changes how `fmt.Println` represents your type.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.