CodeNebula
Go📦Standard Libraryintermediate

io — I/O Primitives

Go · Standard Library · Run with go run

Explanation

The `io` package defines the fundamental I/O interfaces: `io.Reader` (`Read([]byte) (int, error)`), `io.Writer` (`Write([]byte) (int, error)`), `io.Closer`, `io.Seeker`, and their combinations (`io.ReadWriter`, `io.ReadCloser`, etc.). `io.Copy` streams from any Reader to any Writer. `io.ReadAll` reads everything into memory. `io.LimitReader` caps the bytes read.

Real-World Scenario

Proxying an HTTP response body to a file: `io.Copy(file, response.Body)` streams the data without loading it all into memory — critical for large file downloads.

Quick Snippet

snippet.go
import "io"

// Stream from reader to writer
n, err := io.Copy(dst, src) // returns bytes copied

// Read everything (use only when size is bounded)
data, err := io.ReadAll(r)

// Limit reader to prevent oversized inputs
limited := io.LimitReader(r, 1<<20) // max 1 MB
data, err = io.ReadAll(limited)

// MultiWriter — write to multiple destinations simultaneously
multi := io.MultiWriter(file, os.Stdout)
fmt.Fprintln(multi, "goes to both")

Full Example

io_basics.go
// Compile: go run io_basics.go
// Output:
//   copied 13 bytes
//   read back: Hello, CodeNebula
//   limited: Hello
package main

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

func main() {
	// io.Copy streams from any Reader to any Writer
	src := strings.NewReader("Hello, CodeNebula")
	var dst bytes.Buffer
	n, _ := io.Copy(&dst, src)
	fmt.Println("copied", n, "bytes")
	fmt.Println("read back:", dst.String())

	// io.LimitReader caps how much is read
	limited := io.LimitReader(strings.NewReader("Hello, World"), 5)
	data, _ := io.ReadAll(limited)
	fmt.Println("limited:", string(data))
}
Run command
go run io_basics.go