Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Standard Library Interfaces: io.Reader and io.Writer | Pointers, Memory, and Advanced Features
Advanced Go

bookStandard Library Interfaces: io.Reader and io.Writer

Sveip for å vise menyen

Understanding io.Reader and io.Writer

The io.Reader and io.Writer interfaces in Go define core methods for input and output operations:

  • io.Reader requires a Read(p []byte) (n int, err error) method;
  • io.Writer requires a Write(p []byte) (n int, err error) method.

Many types in the Go standard library—such as os.File, bytes.Buffer, and net.Conn—implement these interfaces. This means you can use these types interchangeably in functions that expect an io.Reader or io.Writer, without knowing the underlying type.

main.go

main.go

copy
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
package main import ( "fmt" "io" "os" "strings" ) func main() { // Example 1: Reading from a string using io.Reader reader := strings.NewReader("Hello, io.Reader!") buf := make([]byte, 8) for { n, err := reader.Read(buf) if err == io.EOF { break } fmt.Printf("Read %d bytes: %q\n", n, buf[:n]) } fmt.Println() // Example 2: Writing to a file using io.Writer file, err := os.Create("output.txt") if err != nil { fmt.Println("Failed to create file:", err) return } defer file.Close() writer := file msg := "Hello, io.Writer!\n" n, err := writer.Write([]byte(msg)) if err != nil { fmt.Println("Failed to write to file:", err) return } fmt.Printf("Wrote %d bytes to output.txt\n", n) // Example 3: Copying from a reader to a writer input := strings.NewReader("Copy this line using io.Copy.\n") fmt.Print("Copying to stdout: ") io.Copy(os.Stdout, input) }

Enabling Polymorphic I/O

By designing your code to accept io.Reader or io.Writer parameters, you allow any compatible type to be used for input or output. This approach provides:

  • Flexibility to swap between files, network connections, or in-memory buffers;
  • Reusable functions that operate on any data source or destination supporting the interface;
  • Simplified testing by using mock implementations.

This polymorphism is a cornerstone of Go's I/O system, making your code more modular and adaptable.

question mark

Which statements about the io.Reader and io.Writer interfaces are correct?

Select all correct answers

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 2
some-alt