Go
Beginner
1 min read
Common Standard Library Interfaces
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())
}