Defines fundamental I/O interfaces (Reader, Writer, Closer) used throughout the Go standard library. The bufio package builds on top of these for buffered I/O.
Import: import "io" | Docs: pkg.go.dev/io
| Name | Signature / Value | Description |
|---|---|---|
| io.Reader | interface { Read(p []byte) (n int, err error) } | Anything readable |
| io.Writer | interface { Write(p []byte) (n int, err error) } | Anything writable |
| io.Closer | interface { Close() error } | Anything closeable |
| io.ReadWriter | interface | Combines Reader and Writer |
| io.ReadCloser | interface | Combines Reader and Closer |
| io.Copy | func Copy(dst Writer, src Reader) (written int64, err error) | Copy from src to dst |
| io.CopyN | func CopyN(dst Writer, src Reader, n int64) (written int64, err error) | Copy exactly n bytes |
| io.ReadAll | func ReadAll(r Reader) ([]byte, error) | Read all bytes from a Reader |
| io.WriteString | func WriteString(w Writer, s string) (n int, err error) | Write a string to a Writer |
| io.Discard | var Discard Writer | Writer that discards all data written |
| io.EOF | var EOF = errors.New("EOF") | Returned when no more input is available |
| io.NopCloser | func NopCloser(r Reader) ReadCloser | Wrap Reader with no-op Close method |
| io.LimitReader | func LimitReader(r Reader, n int64) Reader | Wrap Reader that stops after n bytes |
| io.MultiReader | func MultiReader(readers ...Reader) Reader | Concatenate multiple Readers |
| io.MultiWriter | func MultiWriter(writers ...Writer) Writer | Write to multiple Writers simultaneously |
| io.Pipe | func Pipe() (*PipeReader, *PipeWriter) | Create synchronous in-memory pipe |
| io.TeeReader | func TeeReader(r Reader, w Writer) Reader | Read from r while copying to w |
Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
// io.Copy — copy a reader to a writer
r := strings.NewReader("Hello, io package!\n")
n, err := io.Copy(os.Stdout, r)
fmt.Printf("Copied %d bytes, err=%v\n", n, err)
// io.ReadAll — read everything from a Reader
r2 := strings.NewReader("Read all of this text")
data, _ := io.ReadAll(r2)
fmt.Println("ReadAll:", string(data))
// io.LimitReader — read at most N bytes
r3 := strings.NewReader("Only first 5 chars please")
limited := io.LimitReader(r3, 5)
result, _ := io.ReadAll(limited)
fmt.Println("Limited:", string(result))
// io.MultiWriter — write to stdout AND a file simultaneously
f, _ := os.Create("tee_out.txt")
defer f.Close()
mw := io.MultiWriter(os.Stdout, f)
fmt.Fprintln(mw, "This goes to BOTH stdout and file!")
// io.TeeReader — read + copy simultaneously
r4 := strings.NewReader("tee this content")
tr := io.TeeReader(r4, os.Stdout)
io.ReadAll(tr)
fmt.Println()
os.Remove("tee_out.txt")
}
// go run main.go