file, err := os.Open("file.txt") if err != nil { panic(err) } defer file.Close() // Using a buffered reader for efficient reading reader := bufio.NewReader(file) // Using a writer to write to the same file writer := bufio.NewWriter(file) // Using ReadWriter to read from and write to the same file rw := bufio.NewReadWriter(reader, writer) // Reading from the file line, err := rw.ReadString('\n') if err != nil { panic(err) } // Writing to the same file _, err = rw.WriteString("Hello World") if err != nil { panic(err) } // Flushing the writer to write the changes to the file err = rw.Flush() if err != nil { panic(err) }
conn, err := net.Dial("tcp", "example.com:80") if err != nil { panic(err) } defer conn.Close() // Using a buffered reader for efficient reading reader := bufio.NewReader(conn) // Using a writer to write to the network connection writer := bufio.NewWriter(conn) // Using ReadWriter to read from and write to the network connection rw := bufio.NewReadWriter(reader, writer) // Reading from the network connection line, err := rw.ReadString('\n') if err != nil { panic(err) } // Writing to the network connection _, err = rw.WriteString("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n") if err != nil { panic(err) } // Flushing the writer to write the changes to the network err = rw.Flush() if err != nil { panic(err) } // Reading from the network connection again line, err = rw.ReadString('\n') if err != nil { panic(err) }In this example, we are using ReadWriter to read from and write to a network connection. We are first dialing a TCP connection to example.com on port 80, creating a buffered reader to read from it, and a buffered writer to write to it. We are then creating a ReadWriter object using these two objects, which allows us to easily read from and write to the network connection using the same object. We read a line from the network connection, and write a HTTP GET request to it. Finally, we flush the writer to write the changes to the network, and read another line from the network connection. The package library for these examples is the "bufio" standard library.