Core Standard Library Interfaces
fmt.Stringer, io.Reader, io.Writer
Core Standard Library Interfaces is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
fmt.Stringer
fmt.Stringer has one method: String() string. Implement it to control how your type appears with fmt.Println and %v:
package main
import "fmt"
type Color int
const (Red Color = iota; Green; Blue)
func (c Color) String() string {
return []string{"Red","Green","Blue"}[c]
}
func main() {
fmt.Println(Red, Green, Blue) // Red Green Blue
}error Interface
The built-in error interface has one method: Error() string. Any type implementing it can be used as an error:
package main
import "fmt"
type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Msg
}
func validate(age int) error {
if age < 0 { return &ValidationError{"age", "must be non-negative"} }
return nil
}
func main() {
fmt.Println(validate(-1))
}io.Reader
io.Reader has one method: Read(p []byte) (n int, err error). Files, HTTP bodies, strings, and buffers all implement it:
package main
import ("fmt"; "strings")
func countBytes(r interface{ Read([]byte)(int,error) }) int {
buf := make([]byte, 512)
total := 0
for {
n, err := r.Read(buf)
total += n
if err != nil { break }
}
return total
}
func main() {
r := strings.NewReader("hello world")
fmt.Println(countBytes(r)) // 11
}io.Writer
io.Writer has one method: Write(p []byte) (n int, err error). Used by fmt.Fprintf, logging, HTTP response writers, etc.:
package main
import ("bytes"; "fmt")
func main() {
var buf bytes.Buffer
fmt.Fprintf(&buf, "Hello, %s!", "Go")
fmt.Println(buf.String()) // Hello, Go!
}io.ReadWriter and io.Closer
Standard library composes small interfaces into larger ones:
package main
import "io"
// io.ReadWriter = io.Reader + io.Writer
// io.ReadCloser = io.Reader + io.Closer
// io.ReadWriteCloser = all three
func process(rw io.ReadWriter) {
buf := make([]byte, 8)
rw.Read(buf)
rw.Write(buf)
}
func main() { _ = process }sort.Interface
sort.Interface requires Len() int, Less(i, j int) bool, and Swap(i, j int):
package main
import ("fmt"; "sort")
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() {
fruits := ByLength{"banana","apple","kiwi"}
sort.Sort(fruits)
fmt.Println([]string(fruits)) // [kiwi apple banana]
}http.Handler
http.Handler has one method: ServeHTTP(ResponseWriter, *Request). Everything in Go's HTTP stack is built on this single interface:
package main
import ("fmt"; "net/http")
type Hello struct{}
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
func main() {
http.ListenAndServe(":8080", Hello{})
}fmt.GoStringer
Implement GoString() string to control the %#v (Go-syntax) representation of your type:
package main
import "fmt"
type Version struct{ Major, Minor int }
func (v Version) GoString() string {
return fmt.Sprintf("Version{%d, %d}", v.Major, v.Minor)
}
func main() {
fmt.Printf("%#v\n", Version{1, 18}) // Version{1, 18}
}encoding.TextMarshaler
Implement MarshalText() ([]byte, error) and UnmarshalText([]byte) error for custom text encoding (JSON strings, YAML, etc.):
package main
import "fmt"
type Status int
const (Active Status = iota; Inactive)
func (s Status) MarshalText() ([]byte, error) {
if s == Active { return []byte("active"), nil }
return []byte("inactive"), nil
}
func main() {
s := Active
b, _ := s.MarshalText()
fmt.Println(string(b)) // active
}Composing Standard Interfaces
Combine standard interfaces with io.TeeReader, io.MultiWriter, etc. to build powerful pipelines without writing any new types:
package main
import ("bytes"; "fmt"; "io"; "strings")
func main() {
r := strings.NewReader("hello")
var buf bytes.Buffer
tee := io.TeeReader(r, &buf)
io.ReadAll(tee)
fmt.Println(buf.String()) // hello
}Quick Check
Which interface must a type implement to be usable as an error in Go?
Recap
Key standard library interfaces:
fmt.Stringer— custom print representationerror— error valuesio.Reader/io.Writer— streaming I/Osort.Interface— custom sortinghttp.Handler— HTTP request handling
Practice Prompt
Implement sort.Interface on a []Person (where Person has Name and Age fields) to sort by age descending. Print the sorted list.
Frequently asked questions
Is the “Core Standard Library Interfaces” lesson free?
Yes — the full text of “Core Standard Library Interfaces” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Core Standard Library Interfaces”?
fmt.Stringer, io.Reader, io.Writer You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Core Standard Library Interfaces” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining and Implementing Interfaces
- Core Standard Library Interfaces
- Type Assertions and Type Switches
- Interface Composition and Best Practices