Go (Golang) io.Writer Example

The io.Writer interface it’s one of Go’s very small interfaces. It has only one method. The Write method. The io.Writer interface is used by many packages in the Go standard library and it represents the ability to write a byte slice into a stream of data. More generically allows you to write data into something that implements the io.Writer interface. Here’s the io.Writer interface definition


type Writer interface {
    Write(p []byte) (n int, err error)
}

The Write method takes the data from the byte slice p writes it into the underlying data stream and returns the number of bytes written n and an error err if there was any.

io.Writer to write to a file

Here’s an example on how io.Writer is used when writing data to a file in Go

package main

import (
	"fmt"
	"os"
)

func main() {
    f, err := os.OpenFile("/tmp/123.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    n, err := f.Write([]byte("writing some data into a file"))
    if err != nil {
        panic(err)
    }
    fmt.Println("wrote %d bytes", n)
}

os.File’s Read is indeed an implementation of the same io.Writer interface which is used to write a byte slice to the underlying file’s data stream. Here’s the definition of os.File.Write

func (f *File) Write(b []byte) (n int, err error)

io.Writer with json encode

In the Go standard library there are a few implementations and examples of the io.Writer interface. One of them is the json/encoding’s NewEncoder method which takes a io.Writer as input and writes the json encoded output into the underlying stream of data that implements the io.Writer.

func NewEncoder(w io.Writer) *Encoder

Here’s an example using a json Encoder

package main

import (
	"fmt"
	"encoding/json"
	"bytes"
)

type user struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

func main() {
    buf := new(bytes.Buffer)
    u := user{
        Name: "bob";,
        Age: 20,
    }
    err := json.NewEncoder(buf).Encode(u)
    if err != nil {
        panic(err)
    }
    fmt.Print(buf.String())
}

This will encode the user struct into a byte slice (see the bytes.Buffer), the bytes.Buffer implements the io.Writer interface which is passed into NewEncoder. Here’s the expected output

{"name:"bob", "age":20}


Got Questions? Join our Slack community