io#

io.Reader and io.Writer#

Based on the UNIX Universal I/O model (see File I/O).

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}
  • Buffer Allocation Philosophy: Passing p []byte as an argument reuses allocated memory and minimizes Garbage Collection (GC) pressure, mirroring C’s read(fd, buf, count).
  • Read Loop (C vs Go):
    • C (read): Returns only a single ssize_t. When the final chunk of N bytes is read, it returns N. A subsequent call is strictly required to receive 0 (EOF), taking N + 1 calls.
    • Go (Read): Returns two values (n int, err error). An implementation may return the last N bytes and io.EOF simultaneously, finishing in N calls.
  • Golden Rule: Always process n > 0 before checking err == io.EOF because Read can return both valid data and io.EOF in the same call.
for {
    n, err := r.Read(buf)
    if n > 0 {
        // Process buf[:n] first
    }
    if err != nil {
        if err == io.EOF {
            break // Reached EOF
        }
        return err
    }
}

io.Seeker#

Identical to the POSIX lseek(fd, offset, whence) system call (see lseek).

type Seeker interface {
    Seek(offset int64, whence int) (int64, error)
}
  • Sets the offset for the next Read or Write.
  • Whence Constants (io package):
    • io.SeekStart (0): Seek relative to the origin of the file (POSIX SEEK_SET)
    • io.SeekCurrent (1): Seek relative to the current offset (POSIX SEEK_CUR)
    • io.SeekEnd (2): Seek relative to the end (POSIX SEEK_END)

bytes and strings Packages#

  • func bytes.NewReader(b []byte) *Reader
  • func strings.NewReader(s string) *Reader
    • These functions create an io.Reader that mimics a file from memory, similar to <() in a shell.
  • type bytes.Buffer struct
    • A variable-sized buffer of bytes with Read and Write methods.
  • type strings.Builder struct
    • Used to efficiently build a string using Write methods. It minimizes memory copying.

# go io