Common standard interfaces
Context
Section titled “Context”The Go standard library defines many useful interfaces. The most common are:
fmt.Stringer– types that can describe themselves as a string (String() string)error– the built‑in error interface (Error() string)io.Readerandio.Writer– for reading and writing byte streamssort.Interface– for sorting custom collections
Example
Section titled “Example”Implement fmt.Stringer for a Person type.
Code example
Section titled “Code example”package main
import "fmt"
type Person struct { Name string Age int}
func (p Person) String() string { return fmt.Sprintf("%s (%d years old)", p.Name, p.Age)}
func main() { alice := Person{"Alice", 30} fmt.Println(alice) // fmt.Print uses String() automatically}Output
Section titled “Output”Alice (30 years old)