Go Package io: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 21: Line 21:
Files opened with <code>[[Go_Package_os#os.Create.28.29|os.Create()]]</code> implement <code>io.Reader</code>.
Files opened with <code>[[Go_Package_os#os.Create.28.29|os.Create()]]</code> implement <code>io.Reader</code>.


==Wrapping a <tt>[]byte</tt> into a <tt>Reader</tt>==
==<span id='WBSR'></span>Wrapping a <tt>[]byte</tt> into a <tt>Reader</tt>==
A <code>[]byte</code> can be wrapped into a <code>Reader</code> with:
A <code>[]byte</code> can be wrapped into a <code>Reader</code> with:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>

Revision as of 18:17, 5 January 2024

External

Internal

Overview

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

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)

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.