0
0
GoConceptBeginner · 3 min read

What is io.Writer Interface in Go: Simple Explanation and Example

The io.Writer interface in Go represents any type that can write data. It has a single method Write(p []byte) (n int, err error) that writes bytes and returns the number written and an error if any.
⚙️

How It Works

Think of io.Writer as a simple contract that says: "I can accept some bytes and write them somewhere." This "somewhere" could be a file, a network connection, or even just memory. If a type agrees to this contract by implementing the Write method, it can be used wherever an io.Writer is expected.

This is like having a universal power plug adapter: no matter what device you have, if it fits the adapter, you can plug it in and it will work. Similarly, any type that implements Write can be plugged into functions that accept an io.Writer, making your code flexible and reusable.

💻

Example

This example shows how to use io.Writer with a bytes.Buffer, which stores written data in memory.

go
package main

import (
	"bytes"
	"fmt"
)

func main() {
	var buf bytes.Buffer // bytes.Buffer implements io.Writer

	// Write a string as bytes to buf
	n, err := buf.Write([]byte("Hello, io.Writer!"))
	if err != nil {
		fmt.Println("Error writing:", err)
		return
	}

	fmt.Printf("Wrote %d bytes.\n", n)
	fmt.Println("Buffer contents:", buf.String())
}
Output
Wrote 16 bytes. Buffer contents: Hello, io.Writer!
🎯

When to Use

Use io.Writer when you want to write data but don't want to limit where it goes. For example, you might write logs to a file, send data over the network, or save it in memory. By coding to the io.Writer interface, your functions become more flexible and easier to test.

Real-world use cases include writing HTTP responses, saving files, or buffering output before sending it somewhere else. It helps you write code that works with many output types without changing your logic.

Key Points

  • io.Writer is a simple interface with one method: Write([]byte) (int, error).
  • Any type implementing Write can be used as an io.Writer.
  • It allows writing data to different destinations in a uniform way.
  • Using io.Writer makes your code flexible and easy to extend.

Key Takeaways

io.Writer is an interface for writing bytes to any destination.
It requires implementing the Write([]byte) (int, error) method.
Using io.Writer makes your code flexible and reusable.
Many Go types like files and buffers implement io.Writer.
Write functions to accept io.Writer to support multiple outputs.