SyntaxStudy
Sign Up
Go Common Standard Library Interfaces
Go Beginner 1 min read

Common Standard Library Interfaces

The Go standard library defines a small set of fundamental interfaces that are widely composed to build larger abstractions. `io.Reader` requires a single method `Read(p []byte) (n int, err error)`, and `io.Writer` requires `Write(p []byte) (n int, err error)`. These two interfaces unlock access to the entire family of streaming functions in the standard library. The `fmt.Stringer` interface requires a `String() string` method and is used by the `fmt` package to obtain a human-readable representation of a value. Similarly, `error` is itself an interface: any type with an `Error() string` method is an error. Implementing these interfaces on your types integrates them naturally with Go tooling and libraries. The `sort.Interface` requires `Len() int`, `Less(i, j int) bool`, and `Swap(i, j int)`, enabling the `sort.Sort` function to sort any collection. Go 1.18 also introduced the `cmp.Ordered` and related generics-based helpers, but the interface-based sort.Interface remains fundamental for custom sorting logic.
Example
package main

import (
    "fmt"
    "io"
    "sort"
    "strings"
)

// Implement fmt.Stringer
type Celsius float64

func (c Celsius) String() string {
    return fmt.Sprintf("%.1f°C", float64(c))
}

// Custom error type (implements error interface)
type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("validation failed on %q: %s", e.Field, e.Message)
}

// Implement sort.Interface on a custom type
type ByLength []string

func (b ByLength) Len() int           { return len(b) }
func (b ByLength) Less(i, j int) bool { return len(b[i]) < len(b[j]) }
func (b ByLength) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

func main() {
    temp := Celsius(100)
    fmt.Println(temp) // uses String() automatically

    err := &ValidationError{Field: "email", Message: "invalid format"}
    fmt.Println(err)

    words := ByLength{"banana", "fig", "kiwi", "apple"}
    sort.Sort(words)
    fmt.Println(words)

    // io.Reader / io.Writer composition
    r  := strings.NewReader("Hello, io interfaces!")
    var sb strings.Builder
    n, _ := io.Copy(&sb, r)
    fmt.Printf("copied %d bytes: %s\n", n, sb.String())
}