Standard Library Interfaces: io.Reader and io.Writer
Swipe um das Menü anzuzeigen
Understanding io.Reader and io.Writer
The io.Reader and io.Writer interfaces in Go define core methods for input and output operations:
io.Readerrequires aRead(p []byte) (n int, err error)method;io.Writerrequires aWrite(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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546package 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.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen