How to use the io.Pipe for inter-goroutine communication and data streaming in Go?

The io.Pipe package in Go provides a way to create an in-memory pipe that allows for inter-goroutine communication and data streaming. Here's how you can use it:

  1. Import the necessary packages:
import ( "io" "fmt" )
  1. Initialize the pipe by calling io.Pipe():
reader, writer := io.Pipe()
  1. Write data to the pipe:
go func() { defer writer.Close() data := []byte("Hello, World!") _, err := writer.Write(data) if err != nil { fmt.Println("Write error:", err) } }()
  1. Read data from the pipe:
go func() { defer reader.Close() buf := make([]byte, 1024) n, err := reader.Read(buf) if err != nil { fmt.Println("Read error:", err) } fmt.Println(string(buf[:n])) // Print the received data }()
  1. Wait for the goroutines to finish:
// Here, you can use a sync.WaitGroup or sleep for some time to allow the goroutines to complete their tasks
  1. Run the program and observe the output:
Hello, World!

By using the io.Pipe, you can establish a communication channel between goroutines, making it easier to pass data or stream it between them. Remember to properly close the reader and writer to avoid resource leaks.