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 []byteas an argument reuses allocated memory and minimizes Garbage Collection (GC) pressure, mirroring C’sread(fd, buf, count). - Read Loop (C vs Go):
- C (
read): Returns only a singlessize_t. When the final chunk ofNbytes is read, it returnsN. A subsequent call is strictly required to receive0(EOF), takingN + 1calls. - Go (
Read): Returns two values(n int, err error). An implementation may return the lastNbytes andio.EOFsimultaneously, finishing inNcalls.
- C (
- Golden Rule: Always process
n > 0before checkingerr == io.EOFbecauseReadcan return both valid data andio.EOFin 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
ReadorWrite. - Whence Constants (
iopackage):io.SeekStart(0): Seek relative to the origin of the file (POSIXSEEK_SET)io.SeekCurrent(1): Seek relative to the current offset (POSIXSEEK_CUR)io.SeekEnd(2): Seek relative to the end (POSIXSEEK_END)
bytes and strings Packages#
func bytes.NewReader(b []byte) *Readerfunc strings.NewReader(s string) *Reader- These functions create an
io.Readerthat mimics a file from memory, similar to<()in a shell.
- These functions create an
type bytes.Buffer struct- A variable-sized buffer of bytes with
ReadandWritemethods.
- A variable-sized buffer of bytes with
type strings.Builder struct- Used to efficiently build a string using
Writemethods. It minimizes memory copying.
- Used to efficiently build a string using