Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Go Index

🌊 io — Core I/O interfaces and utilities

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

📋 Functions, Types & Constants

NameSignature / ValueDescription
io.Readerinterface { Read(p []byte) (n int, err error) }Anything readable
io.Writerinterface { Write(p []byte) (n int, err error) }Anything writable
io.Closerinterface { Close() error }Anything closeable
io.ReadWriterinterfaceCombines Reader and Writer
io.ReadCloserinterfaceCombines Reader and Closer
io.Copyfunc Copy(dst Writer, src Reader) (written int64, err error)Copy from src to dst
io.CopyNfunc CopyN(dst Writer, src Reader, n int64) (written int64, err error)Copy exactly n bytes
io.ReadAllfunc ReadAll(r Reader) ([]byte, error)Read all bytes from a Reader
io.WriteStringfunc WriteString(w Writer, s string) (n int, err error)Write a string to a Writer
io.Discardvar Discard WriterWriter that discards all data written
io.EOFvar EOF = errors.New("EOF")Returned when no more input is available
io.NopCloserfunc NopCloser(r Reader) ReadCloserWrap Reader with no-op Close method
io.LimitReaderfunc LimitReader(r Reader, n int64) ReaderWrap Reader that stops after n bytes
io.MultiReaderfunc MultiReader(readers ...Reader) ReaderConcatenate multiple Readers
io.MultiWriterfunc MultiWriter(writers ...Writer) WriterWrite to multiple Writers simultaneously
io.Pipefunc Pipe() (*PipeReader, *PipeWriter)Create synchronous in-memory pipe
io.TeeReaderfunc TeeReader(r Reader, w Writer) ReaderRead from r while copying to w

💡 Example Program

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

← os  |  🏠 Index  |  strings →