Understand the contract
The Go standard library provides packages for text, files, encoding, time, HTTP and testing. Many packages connect through small interfaces. io.Reader supplies bytes and io.Writer accepts bytes, allowing a function to process a file, buffer or network stream without depending on one concrete storage type.
This block applies the function and error contracts from the previous lessons to input and output. Check errors at every operation that can fail, define the lifetime of open resources and decide how much input your program accepts. Those decisions remain relevant when a local example becomes an HTTP service.
Work through the example
The example copies from a strings.Reader into a bytes.Buffer. io.Copy returns the byte count and an error. The buffer can then expose its content as a string. Both types are in memory, making the reader/writer relationship visible without introducing file paths or network failures.
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
var output bytes.Buffer
n, err := io.Copy(&output, strings.NewReader("hello"))
if err != nil { fmt.Println(err); return }
fmt.Println(n, output.String())
}Watch this boundary
An interface abstracts behavior, not cost. io.ReadAll can allocate for the full input, and an unrestricted io.Copy can run for as long as its source supplies data. Later examples introduce input limits, deadlines and resource closure instead of assuming every input is small and trusted.
Practice with a changed input
Replace the source string with an empty one and inspect the count. Then write a function that accepts io.Reader and returns the number of bytes copied to io.Discard.
Lesson 32 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services