Movatterモバイル変換


[0]ホーム

URL:


io

packagestandard library
go1.25.4Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:2Imported by:1,499,072

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package io provides basic interfaces to I/O primitives.Its primary job is to wrap existing implementations of such primitives,such as those in package os, into shared public interfaces thatabstract the functionality, plus some other related primitives.

Because these interfaces and primitives wrap lower-level operations withvarious implementations, unless otherwise informed clients should notassume they are safe for parallel execution.

Index

Examples

Constants

View Source
const (SeekStart   = 0// seek relative to the origin of the fileSeekCurrent = 1// seek relative to the current offsetSeekEnd     = 2// seek relative to the end)

Seek whence values.

Variables

View Source
var EOF =errors.New("EOF")

EOF is the error returned by Read when no more input is available.(Read must return EOF itself, not an error wrapping EOF,because callers will test for EOF using ==.)Functions should return EOF only to signal a graceful end of input.If the EOF occurs unexpectedly in a structured data stream,the appropriate error is eitherErrUnexpectedEOF or some other errorgiving more detail.

View Source
var ErrClosedPipe =errors.New("io: read/write on closed pipe")

ErrClosedPipe is the error used for read or write operations on a closed pipe.

View Source
var ErrNoProgress =errors.New("multiple Read calls return no data or error")

ErrNoProgress is returned by some clients of aReader whenmany calls to Read have failed to return any data or error,usually the sign of a brokenReader implementation.

View Source
var ErrShortBuffer =errors.New("short buffer")

ErrShortBuffer means that a read required a longer buffer than was provided.

View Source
var ErrShortWrite =errors.New("short write")

ErrShortWrite means that a write accepted fewer bytes than requestedbut failed to return an explicit error.

View Source
var ErrUnexpectedEOF =errors.New("unexpected EOF")

ErrUnexpectedEOF means that EOF was encountered in themiddle of reading a fixed-size block or data structure.

Functions

funcCopy

func Copy(dstWriter, srcReader) (writtenint64, errerror)

Copy copies from src to dst until either EOF is reachedon src or an error occurs. It returns the number of bytescopied and the first error encountered while copying, if any.

A successful Copy returns err == nil, not err == EOF.Because Copy is defined to read from src until EOF, it doesnot treat an EOF from Read as an error to be reported.

If src implementsWriterTo,the copy is implemented by calling src.WriteTo(dst).Otherwise, if dst implementsReaderFrom,the copy is implemented by calling dst.ReadFrom(src).

Example
package mainimport ("io""log""os""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")if _, err := io.Copy(os.Stdout, r); err != nil {log.Fatal(err)}}
Output:some io.Reader stream to be read

funcCopyBufferadded ingo1.5

func CopyBuffer(dstWriter, srcReader, buf []byte) (writtenint64, errerror)

CopyBuffer is identical to Copy except that it stages through theprovided buffer (if one is required) rather than allocating atemporary one. If buf is nil, one is allocated; otherwise if it haszero length, CopyBuffer panics.

If either src implementsWriterTo or dst implementsReaderFrom,buf will not be used to perform the copy.

Example
package mainimport ("io""log""os""strings")func main() {r1 := strings.NewReader("first reader\n")r2 := strings.NewReader("second reader\n")buf := make([]byte, 8)// buf is used here...if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {log.Fatal(err)}// ... reused here also. No need to allocate an extra buffer.if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {log.Fatal(err)}}
Output:first readersecond reader

funcCopyN

func CopyN(dstWriter, srcReader, nint64) (writtenint64, errerror)

CopyN copies n bytes (or until an error) from src to dst.It returns the number of bytes copied and the earliesterror encountered while copying.On return, written == n if and only if err == nil.

If dst implementsReaderFrom, the copy is implemented using it.

Example
package mainimport ("io""log""os""strings")func main() {r := strings.NewReader("some io.Reader stream to be read")if _, err := io.CopyN(os.Stdout, r, 4); err != nil {log.Fatal(err)}}
Output:some

funcPipe

func Pipe() (*PipeReader, *PipeWriter)

Pipe creates a synchronous in-memory pipe.It can be used to connect code expecting anio.Readerwith code expecting anio.Writer.

Reads and Writes on the pipe are matched one to oneexcept when multiple Reads are needed to consume a single Write.That is, each Write to thePipeWriter blocks until it has satisfiedone or more Reads from thePipeReader that fully consumethe written data.The data is copied directly from the Write to the correspondingRead (or Reads); there is no internal buffering.

It is safe to call Read and Write in parallel with each other or with Close.Parallel calls to Read and parallel calls to Write are also safe:the individual calls will be gated sequentially.

Example
package mainimport ("fmt""io""log""os")func main() {r, w := io.Pipe()go func() {fmt.Fprint(w, "some io.Reader stream to be read\n")w.Close()}()if _, err := io.Copy(os.Stdout, r); err != nil {log.Fatal(err)}}
Output:some io.Reader stream to be read

funcReadAlladded ingo1.16

func ReadAll(rReader) ([]byte,error)

ReadAll reads from r until an error or EOF and returns the data it read.A successful call returns err == nil, not err == EOF. Because ReadAll isdefined to read from src until EOF, it does not treat an EOF from Readas an error to be reported.

Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")b, err := io.ReadAll(r)if err != nil {log.Fatal(err)}fmt.Printf("%s", b)}
Output:Go is a general-purpose language designed with systems programming in mind.

funcReadAtLeast

func ReadAtLeast(rReader, buf []byte, minint) (nint, errerror)

ReadAtLeast reads from r into buf until it has read at least min bytes.It returns the number of bytes copied and an error if fewer bytes were read.The error is EOF only if no bytes were read.If an EOF happens after reading fewer than min bytes,ReadAtLeast returnsErrUnexpectedEOF.If min is greater than the length of buf, ReadAtLeast returnsErrShortBuffer.On return, n >= min if and only if err == nil.If r returns an error having read at least min bytes, the error is dropped.

Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")buf := make([]byte, 14)if _, err := io.ReadAtLeast(r, buf, 4); err != nil {log.Fatal(err)}fmt.Printf("%s\n", buf)// buffer smaller than minimal read size.shortBuf := make([]byte, 3)if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {fmt.Println("error:", err)}// minimal read size bigger than io.Reader streamlongBuf := make([]byte, 64)if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {fmt.Println("error:", err)}}
Output:some io.Readererror: short buffererror: unexpected EOF

funcReadFull

func ReadFull(rReader, buf []byte) (nint, errerror)

ReadFull reads exactly len(buf) bytes from r into buf.It returns the number of bytes copied and an error if fewer bytes were read.The error is EOF only if no bytes were read.If an EOF happens after reading some but not all the bytes,ReadFull returnsErrUnexpectedEOF.On return, n == len(buf) if and only if err == nil.If r returns an error having read at least len(buf) bytes, the error is dropped.

Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")buf := make([]byte, 4)if _, err := io.ReadFull(r, buf); err != nil {log.Fatal(err)}fmt.Printf("%s\n", buf)// minimal read size bigger than io.Reader streamlongBuf := make([]byte, 64)if _, err := io.ReadFull(r, longBuf); err != nil {fmt.Println("error:", err)}}
Output:someerror: unexpected EOF

funcWriteString

func WriteString(wWriter, sstring) (nint, errerror)

WriteString writes the contents of the string s to w, which accepts a slice of bytes.If w implementsStringWriter, [StringWriter.WriteString] is invoked directly.Otherwise, [Writer.Write] is called exactly once.

Example
package mainimport ("io""log""os")func main() {if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil {log.Fatal(err)}}
Output:Hello World

Types

typeByteReader

type ByteReader interface {ReadByte() (byte,error)}

ByteReader is the interface that wraps the ReadByte method.

ReadByte reads and returns the next byte from the input orany error encountered. If ReadByte returns an error, no inputbyte was consumed, and the returned byte value is undefined.

ReadByte provides an efficient interface for byte-at-timeprocessing. AReader that does not implement ByteReadercan be wrapped using bufio.NewReader to add this method.

typeByteScanner

type ByteScanner interface {ByteReaderUnreadByte()error}

ByteScanner is the interface that adds the UnreadByte method to thebasic ReadByte method.

UnreadByte causes the next call to ReadByte to return the last byte read.If the last operation was not a successful call to ReadByte, UnreadByte mayreturn an error, unread the last byte read (or the byte prior to thelast-unread byte), or (in implementations that support theSeeker interface)seek to one byte before the current offset.

typeByteWriteradded ingo1.1

type ByteWriter interface {WriteByte(cbyte)error}

ByteWriter is the interface that wraps the WriteByte method.

typeCloser

type Closer interface {Close()error}

Closer is the interface that wraps the basic Close method.

The behavior of Close after the first call is undefined.Specific implementations may document their own behavior.

typeLimitedReader

type LimitedReader struct {RReader// underlying readerNint64// max bytes remaining}

A LimitedReader reads from R but limits the amount ofdata returned to just N bytes. Each call to Readupdates N to reflect the new amount remaining.Read returns EOF when N <= 0 or when the underlying R returns EOF.

func (*LimitedReader)Read

func (l *LimitedReader) Read(p []byte) (nint, errerror)

typeOffsetWriteradded ingo1.20

type OffsetWriter struct {// contains filtered or unexported fields}

An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.

funcNewOffsetWriteradded ingo1.20

func NewOffsetWriter(wWriterAt, offint64) *OffsetWriter

NewOffsetWriter returns anOffsetWriter that writes to wstarting at offset off.

func (*OffsetWriter)Seekadded ingo1.20

func (o *OffsetWriter) Seek(offsetint64, whenceint) (int64,error)

func (*OffsetWriter)Writeadded ingo1.20

func (o *OffsetWriter) Write(p []byte) (nint, errerror)

func (*OffsetWriter)WriteAtadded ingo1.20

func (o *OffsetWriter) WriteAt(p []byte, offint64) (nint, errerror)

typePipeReader

type PipeReader struct {// contains filtered or unexported fields}

A PipeReader is the read half of a pipe.

func (*PipeReader)Close

func (r *PipeReader) Close()error

Close closes the reader; subsequent writes to thewrite half of the pipe will return the errorErrClosedPipe.

func (*PipeReader)CloseWithError

func (r *PipeReader) CloseWithError(errerror)error

CloseWithError closes the reader; subsequent writesto the write half of the pipe will return the error err.

CloseWithError never overwrites the previous error if it existsand always returns nil.

func (*PipeReader)Read

func (r *PipeReader) Read(data []byte) (nint, errerror)

Read implements the standard Read interface:it reads data from the pipe, blocking until a writerarrives or the write end is closed.If the write end is closed with an error, that error isreturned as err; otherwise err is EOF.

typePipeWriter

type PipeWriter struct {// contains filtered or unexported fields}

A PipeWriter is the write half of a pipe.

func (*PipeWriter)Close

func (w *PipeWriter) Close()error

Close closes the writer; subsequent reads from theread half of the pipe will return no bytes and EOF.

func (*PipeWriter)CloseWithError

func (w *PipeWriter) CloseWithError(errerror)error

CloseWithError closes the writer; subsequent reads from theread half of the pipe will return no bytes and the error err,or EOF if err is nil.

CloseWithError never overwrites the previous error if it existsand always returns nil.

func (*PipeWriter)Write

func (w *PipeWriter) Write(data []byte) (nint, errerror)

Write implements the standard Write interface:it writes data to the pipe, blocking until one or more readershave consumed all the data or the read end is closed.If the read end is closed with an error, that err isreturned as err; otherwise err isErrClosedPipe.

typeReadCloser

type ReadCloser interface {ReaderCloser}

ReadCloser is the interface that groups the basic Read and Close methods.

funcNopCloseradded ingo1.16

func NopCloser(rReader)ReadCloser

NopCloser returns aReadCloser with a no-op Close method wrappingthe providedReader r.If r implementsWriterTo, the returnedReadCloser will implementWriterToby forwarding calls to r.

typeReadSeekCloseradded ingo1.16

type ReadSeekCloser interface {ReaderSeekerCloser}

ReadSeekCloser is the interface that groups the basic Read, Seek and Closemethods.

typeReadSeeker

type ReadSeeker interface {ReaderSeeker}

ReadSeeker is the interface that groups the basic Read and Seek methods.

typeReadWriteCloser

type ReadWriteCloser interface {ReaderWriterCloser}

ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.

typeReadWriteSeeker

type ReadWriteSeeker interface {ReaderWriterSeeker}

ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.

typeReadWriter

type ReadWriter interface {ReaderWriter}

ReadWriter is the interface that groups the basic Read and Write methods.

typeReader

type Reader interface {Read(p []byte) (nint, errerror)}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytesread (0 <= n <= len(p)) and any error encountered. Even if Readreturns n < len(p), it may use all of p as scratch space during the call.If some data is available but not len(p) bytes, Read conventionallyreturns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition aftersuccessfully reading n > 0 bytes, it returns the number ofbytes read. It may return the (non-nil) error from the same callor return the error (and n == 0) from a subsequent call.An instance of this general case is that a Reader returninga non-zero number of bytes at the end of the input stream mayreturn either err == EOF or err == nil. The next Read shouldreturn 0, EOF.

Callers should always process the n > 0 bytes returned beforeconsidering the error err. Doing so correctly handles I/O errorsthat happen after reading some bytes and also both of theallowed EOF behaviors.

If len(p) == 0, Read should always return n == 0. It may return anon-nil error if some error condition is known, such as EOF.

Implementations of Read are discouraged from returning azero byte count with a nil error, except when len(p) == 0.Callers should treat a return of 0 and nil as indicating thatnothing happened; in particular it does not indicate EOF.

Implementations must not retain p.

funcLimitReader

func LimitReader(rReader, nint64)Reader

LimitReader returns a Reader that reads from rbut stops with EOF after n bytes.The underlying implementation is a *LimitedReader.

Example
package mainimport ("io""log""os""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")lr := io.LimitReader(r, 4)if _, err := io.Copy(os.Stdout, lr); err != nil {log.Fatal(err)}}
Output:some

funcMultiReader

func MultiReader(readers ...Reader)Reader

MultiReader returns a Reader that's the logical concatenation ofthe provided input readers. They're read sequentially. Once allinputs have returned EOF, Read will return EOF. If any of the readersreturn a non-nil, non-EOF error, Read will return that error.

Example
package mainimport ("io""log""os""strings")func main() {r1 := strings.NewReader("first reader ")r2 := strings.NewReader("second reader ")r3 := strings.NewReader("third reader\n")r := io.MultiReader(r1, r2, r3)if _, err := io.Copy(os.Stdout, r); err != nil {log.Fatal(err)}}
Output:first reader second reader third reader

funcTeeReader

func TeeReader(rReader, wWriter)Reader

TeeReader returns aReader that writes to w what it reads from r.All reads from r performed through it are matched withcorresponding writes to w. There is no internal buffering -the write must complete before the read completes.Any error encountered while writing is reported as a read error.

Example
package mainimport ("io""log""os""strings")func main() {var r io.Reader = strings.NewReader("some io.Reader stream to be read\n")r = io.TeeReader(r, os.Stdout)// Everything read from r will be copied to stdout.if _, err := io.ReadAll(r); err != nil {log.Fatal(err)}}
Output:some io.Reader stream to be read

typeReaderAt

type ReaderAt interface {ReadAt(p []byte, offint64) (nint, errerror)}

ReaderAt is the interface that wraps the basic ReadAt method.

ReadAt reads len(p) bytes into p starting at offset off in theunderlying input source. It returns the number of bytesread (0 <= n <= len(p)) and any error encountered.

When ReadAt returns n < len(p), it returns a non-nil errorexplaining why more bytes were not returned. In this respect,ReadAt is stricter than Read.

Even if ReadAt returns n < len(p), it may use all of p as scratchspace during the call. If some data is available but not len(p) bytes,ReadAt blocks until either all the data is available or an error occurs.In this respect ReadAt is different from Read.

If the n = len(p) bytes returned by ReadAt are at the end of theinput source, ReadAt may return either err == EOF or err == nil.

If ReadAt is reading from an input source with a seek offset,ReadAt should not affect nor be affected by the underlyingseek offset.

Clients of ReadAt can execute parallel ReadAt calls on thesame input source.

Implementations must not retain p.

typeReaderFrom

type ReaderFrom interface {ReadFrom(rReader) (nint64, errerror)}

ReaderFrom is the interface that wraps the ReadFrom method.

ReadFrom reads data from r until EOF or error.The return value n is the number of bytes read.Any error except EOF encountered during the read is also returned.

TheCopy function usesReaderFrom if available.

typeRuneReader

type RuneReader interface {ReadRune() (rrune, sizeint, errerror)}

RuneReader is the interface that wraps the ReadRune method.

ReadRune reads a single encoded Unicode characterand returns the rune and its size in bytes. If no character isavailable, err will be set.

typeRuneScanner

type RuneScanner interface {RuneReaderUnreadRune()error}

RuneScanner is the interface that adds the UnreadRune method to thebasic ReadRune method.

UnreadRune causes the next call to ReadRune to return the last rune read.If the last operation was not a successful call to ReadRune, UnreadRune mayreturn an error, unread the last rune read (or the rune prior to thelast-unread rune), or (in implementations that support theSeeker interface)seek to the start of the rune before the current offset.

typeSectionReader

type SectionReader struct {// contains filtered or unexported fields}

SectionReader implements Read, Seek, and ReadAt on a sectionof an underlyingReaderAt.

Example
package mainimport ("io""log""os""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")s := io.NewSectionReader(r, 5, 17)if _, err := io.Copy(os.Stdout, s); err != nil {log.Fatal(err)}}
Output:io.Reader stream

funcNewSectionReader

func NewSectionReader(rReaderAt, offint64, nint64) *SectionReader

NewSectionReader returns aSectionReader that reads from rstarting at offset off and stops with EOF after n bytes.

func (*SectionReader)Outeradded ingo1.22.0

func (s *SectionReader) Outer() (rReaderAt, offint64, nint64)

Outer returns the underlyingReaderAt and offsets for the section.

The returned values are the same that were passed toNewSectionReaderwhen theSectionReader was created.

func (*SectionReader)Read

func (s *SectionReader) Read(p []byte) (nint, errerror)
Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")s := io.NewSectionReader(r, 5, 17)buf := make([]byte, 9)if _, err := s.Read(buf); err != nil {log.Fatal(err)}fmt.Printf("%s\n", buf)}
Output:io.Reader

func (*SectionReader)ReadAt

func (s *SectionReader) ReadAt(p []byte, offint64) (nint, errerror)
Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")s := io.NewSectionReader(r, 5, 17)buf := make([]byte, 6)if _, err := s.ReadAt(buf, 10); err != nil {log.Fatal(err)}fmt.Printf("%s\n", buf)}
Output:stream

func (*SectionReader)Seek

func (s *SectionReader) Seek(offsetint64, whenceint) (int64,error)
Example
package mainimport ("io""log""os""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")s := io.NewSectionReader(r, 5, 17)if _, err := s.Seek(10, io.SeekStart); err != nil {log.Fatal(err)}if _, err := io.Copy(os.Stdout, s); err != nil {log.Fatal(err)}}
Output:stream

func (*SectionReader)Size

func (s *SectionReader) Size()int64

Size returns the size of the section in bytes.

Example
package mainimport ("fmt""io""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")s := io.NewSectionReader(r, 5, 17)fmt.Println(s.Size())}
Output:17

typeSeeker

type Seeker interface {Seek(offsetint64, whenceint) (int64,error)}

Seeker is the interface that wraps the basic Seek method.

Seek sets the offset for the next Read or Write to offset,interpreted according to whence:SeekStart means relative to the start of the file,SeekCurrent means relative to the current offset, andSeekEnd means relative to the end(for example, offset = -2 specifies the penultimate byte of the file).Seek returns the new offset relative to the start of thefile or an error, if any.

Seeking to an offset before the start of the file is an error.Seeking to any positive offset may be allowed, but if the new offset exceedsthe size of the underlying object the behavior of subsequent I/O operationsis implementation-dependent.

typeStringWriteradded ingo1.12

type StringWriter interface {WriteString(sstring) (nint, errerror)}

StringWriter is the interface that wraps the WriteString method.

typeWriteCloser

type WriteCloser interface {WriterCloser}

WriteCloser is the interface that groups the basic Write and Close methods.

typeWriteSeeker

type WriteSeeker interface {WriterSeeker}

WriteSeeker is the interface that groups the basic Write and Seek methods.

typeWriter

type Writer interface {Write(p []byte) (nint, errerror)}

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying data stream.It returns the number of bytes written from p (0 <= n <= len(p))and any error encountered that caused the write to stop early.Write must return a non-nil error if it returns n < len(p).Write must not modify the slice data, even temporarily.

Implementations must not retain p.

var DiscardWriter = discard{}

Discard is aWriter on which all Write calls succeedwithout doing anything.

funcMultiWriter

func MultiWriter(writers ...Writer)Writer

MultiWriter creates a writer that duplicates its writes to all theprovided writers, similar to the Unix tee(1) command.

Each write is written to each listed writer, one at a time.If a listed writer returns an error, that overall write operationstops and returns the error; it does not continue down the list.

Example
package mainimport ("fmt""io""log""strings")func main() {r := strings.NewReader("some io.Reader stream to be read\n")var buf1, buf2 strings.Builderw := io.MultiWriter(&buf1, &buf2)if _, err := io.Copy(w, r); err != nil {log.Fatal(err)}fmt.Print(buf1.String())fmt.Print(buf2.String())}
Output:some io.Reader stream to be readsome io.Reader stream to be read

typeWriterAt

type WriterAt interface {WriteAt(p []byte, offint64) (nint, errerror)}

WriterAt is the interface that wraps the basic WriteAt method.

WriteAt writes len(p) bytes from p to the underlying data streamat offset off. It returns the number of bytes written from p (0 <= n <= len(p))and any error encountered that caused the write to stop early.WriteAt must return a non-nil error if it returns n < len(p).

If WriteAt is writing to a destination with a seek offset,WriteAt should not affect nor be affected by the underlyingseek offset.

Clients of WriteAt can execute parallel WriteAt calls on the samedestination if the ranges do not overlap.

Implementations must not retain p.

typeWriterTo

type WriterTo interface {WriteTo(wWriter) (nint64, errerror)}

WriterTo is the interface that wraps the WriteTo method.

WriteTo writes data to w until there's no more data to write orwhen an error occurs. The return value n is the number of byteswritten. Any error encountered during the write is also returned.

The Copy function uses WriterTo if available.

Source Files

View all Source files

Directories

PathSynopsis
Package fs defines basic interfaces to a file system.
Package fs defines basic interfaces to a file system.
Package ioutil implements some I/O utility functions.
Package ioutil implements some I/O utility functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp