"bytes.Buffer" and the "io.Writer" Interface for Go
Question: When attempting to implement the "io.Writer" interface with a "bytes.Buffer" object in Go, an error message "bytes.Buffer does not implement io.Writer" is encountered. How can this error be resolved?
Answer:
To resolve this error, a pointer to the "bytes.Buffer" should be passed instead of the buffer itself. This is because the "Write" method of the "io.Writer" interface has a pointer receiver, while the "bytes.Buffer" type has a value receiver for its "Write" method.
Here's an example that demonstrates how to correctly implement this:
import "bufio" import "bytes" func main() { var b bytes.Buffer foo := bufio.NewWriter(&b) }
By passing a pointer to the "bytes.Buffer", the code can correctly implement the "io.Writer" interface, as it is now using the pointer receiver form of the "Write" method.
The above is the detailed content of Why Doesn't `bytes.Buffer` Implement `io.Writer` Directly in Go?. For more information, please follow other related articles on the PHP Chinese website!