Quidest?

Stringers interface in Go

ยท Lorenzo Drumond

One of the most common interfaces is Stringer defined by the fmt package:

1type Stringer interface {
2  String() string
3}

A Stringer is a type that can describe itself as a string. The fmt package look for this interface to print values.

E.g.:

 1package main
 2
 3import "fmt"
 4
 5type Person struct {
 6	Name string
 7	Age  int
 8}
 9
10func (p Person) String() string {
11	return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
12}
13
14func main() {
15	a := Person{"Arthur Dent", 42}
16	z := Person{"Zaphod Beeblebrox", 9001}
17	fmt.Println(a, z)
18}
19
20// Output:
21// Arthur Dent (42 years) Zaphod Beeblebrox (9001 years)

References

#golang #for_the_love_of_go #heap #methods #stringers #pass_by #programming #reference #pointer #interface #fmt #stack #print #string #value