Go Package io: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 12: Line 12:


The <tt>io</tt> package consists of a few functions, but mostly interfaces used by other packages.
The <tt>io</tt> package consists of a few functions, but mostly interfaces used by other packages.
=<tt>io.EOF</tt>=
The error returned by I/O operations that encounter the end of file. It can be tested with:
<syntaxhighlight lang='go'>
_, err := ...
if errors.Is(err, io.EOF) {
  // is EOF
  ...
}
</syntaxhighlight>


=<tt>Reader</tt>=
=<tt>Reader</tt>=

Revision as of 21:17, 29 February 2024

External

Internal

Overview

The io package consists of a few functions, but mostly interfaces used by other packages.

io.EOF

The error returned by I/O operations that encounter the end of file. It can be tested with:

_, err := ...
if errors.Is(err, io.EOF) {
  // is EOF 
  ...
}

Reader

https://golang.org/pkg/io/#Reader

An interface that exposes Read().

Readers can be used to unmarshall JSON into structs as shown here:

Unmarshalling JSON from a Reader into a struct

Files opened with os.Create() implement io.Reader.

Wrapping a []byte into a Reader

A []byte can be wrapped into a Reader with:

import "bytes"

bs := []byte("something")
r := bytes.NewReader(bs)

Getting a Reader from a string

s := "some string"
reader := strings.NewReader(s)

Writer

https://golang.org/pkg/io/#Writer

Files opened with os.Create() implement io.Writer.

Closer

https://golang.org/pkg/io/#Closer

Files opened with os.Create() implement io.Closer.

ReadCloser

An interface that exposes basic Read() and Close() methods. The http.Request body is a ReadCloser. See Reader.