SoFunction
Updated on 2025-03-10

One article will help you master the sum in Go language I/O operations

In Go, and are two very important interfaces that play a key role in many standard libraries, especially in I/O operations. Understanding their functions and usage is the basis for mastering Go language I/O operations.

1. and interface

The Go language provides flexible I/O operations through interfaces, and these two core interfaces are used to define basic input and output operations.

interface

The interface is used to read data from data sources (such as files, network connections, memory, etc.). Its definition is very simple:

package io

type Reader interface {
    Read(p []byte) (n int, err error)
}

Read(p []byte): The Read method reads data of up to len(p) bytes from the data source and stores it in p, returning the actual number of bytes n and the possible error err. The returned err can be nil (representing success) or other errors, such as EOF (end of file) error, indicating that the data has been read.

Common implementations include , , , etc.

interface

The interface is used to write data to a data target (such as files, network connections, memory, etc.). Its definition is as follows:

package io

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

Write(p []byte): The Write method writes the data in p to the target data source and returns the actual number of bytes written n and the possible error err.

Common implementations include , , , etc.

2. Examples of usage of and

Example 1: Use

Let's look at a simple example using read data from a file and print it to standard output.

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// Open a file	file, err := ("")
	if err != nil {
		("Error opening file:", err)
		return
	}
	defer ()

	// Create a buffer	buf := make([]byte, 8) // 8 bytes per read
	// Read data from the file	for {
		n, err := (buf)
		if err ==  {
			break // Reading is completed		}
		if err != nil {
			("Error reading file:", err)
			return
		}

		// Print the read content		(string(buf[:n]))
	}
}

In this example:

  • file implements the interface.
  • We use (buf) to read data from a file and store buf.
  • Read up to 8 bytes per time until EOF is encountered (end of file).

Example 2: Use

Next, let's look at a simple example, using write data to a file.

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// Create a file	file, err := ("")
	if err != nil {
		("Error creating file:", err)
		return
	}
	defer ()

	// What to write	data := "Hello, Go I/O!\n"

	// Write data to a file	n, err := ([]byte(data))
	if err != nil {
		("Error writing to file:", err)
		return
	}

	("Wrote %d bytes to file\n", n)
}

In this example:

  • file implements the interface.
  • We write data to the file via ([]byte(data)).

Example 3: Combination and

I/O operations in Go often involve reading data from a Reader and then writing the data to a Writer. For example, copy the contents of one file to another:

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// Open source file	src, err := ("")
	if err != nil {
		("Error opening source file:", err)
		return
	}
	defer ()

	// Create target file	dst, err := ("")
	if err != nil {
		("Error creating destination file:", err)
		return
	}
	defer ()

	// Copy the file content from src to dst	n, err := (dst, src)
	if err != nil {
		("Error copying file:", err)
		return
	}

	("Successfully copied %d bytes\n", n)
}

In this example:

src implements the interface (we read data from a file).

dst implements the interface (we write data to a file).

The function reads and writes the data in src to dst until the reading is complete.

3. Some important implementations of

is a common implementation of , and , which acts as a buffer in memory to read and write data. Can be used to process string or binary data.

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Create a new Buffer	var buf 

	// Write data using Writer interface	([]byte("Hello, Go!"))

	// Use the Reader interface to read data	data := ()
	(data) // Output: Hello, Go!}

Types also implement and interface. It allows you to read and write files directly.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Open a file (read-only mode)	file, err := ("")
	if err != nil {
		("Error opening file:", err)
		return
	}
	defer ()

	// Read file content	buf := make([]byte, 1024)
	n, err := (buf)
	if err != nil {
		("Error reading file:", err)
		return
	}

	("Read %d bytes: %s\n", n, buf[:n])
}

4. Advanced applications of and

1.

It is a very useful function that can pass the output of a Reader to another Writer at the same time, which is equivalent to copying a copy of the data. Can be used for logging or debugging.

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// Create a file	file, err := ("")
	if err != nil {
		("Error creating file:", err)
		return
	}
	defer ()

	// Create a TeeReader, read from stdin, and write to the file at the same time	tee := (, file)

	// Read input from tee	buf := make([]byte, 1024)
	n, err := (buf)
	if err != nil && err !=  {
		("Error reading input:", err)
		return
	}

	// Output the read data	("Read %d bytes: %s\n", n, buf[:n])
}

In this example, TeeReader will write the input of stdin to the file at the same time.

2.

Used to create a pipeline whose Reader and Writer can be concurrently operated in different goroutines, suitable for pipeline streaming.

package main

import (
	"fmt"
	"io"
)

func main() {
	// Create a pipeline	pr, pw := ()

	// Write data in a goroutine	go func() {
		defer ()
		([]byte("Hello, Pipe!"))
	}()

	// Read data	buf := make([]byte, 1024)
	n, _ := (buf)
	("Read from pipe: %s\n", string(buf[:n]))
}

Summarize

: Used to read data from a data source, the Read method reads the data into a given byte slice.

: Used to write data to the target, the Write method writes data to the specified target.

This is the article about this article about how to master the G and I/O operations in Go language. For more related Go and content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!