Home

fmtStringer

FmtStringer is an informal term used to describe a type that provides a custom string representation for formatting with the fmt package in Go. The official concept is the Stringer interface, defined in the fmt package as type Stringer interface { String() string }. A type that implements String() string is effectively a fmtStringer because fmt-based formatting will use that method to obtain the textual representation.

The mechanism lets developers control how their types are displayed when printed with the fmt family of

Example:

type Point struct { X, Y int }

func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.X, p.Y) }

With this, fmt.Println(Point{2, 3}) outputs (2, 3). Implementing String() is a lightweight way to improve the readability

Advanced formatting can be achieved by implementing the Format method from the Formatter interface, which allows

functions,
such
as
fmt.Printf,
fmt.Println,
or
fmt.Sprintf.
If
a
value
implements
Stringer,
the
fmt
package
uses
the
result
of
its
String()
method
for
formatting
with
the
%v
and
%s
verbs.
If
a
type
does
not
implement
Stringer,
fmt
applies
its
default
formatting
rules
for
the
underlying
type.
of
logs
and
user-facing
text
without
changing
the
underlying
data
structure.
per-verb
control
of
output.
If
a
type
implements
both
Formatter
and
Stringer,
the
Format
method
takes
precedence
for
the
corresponding
verbs,
enabling
fine-grained
formatting
while
still
supporting
a
default
String()
representation.