In order to actually change struct
fields in a method, you need a pointer-type receiver. I understand that.
Why can't I satisfy the io.Writer
interface with a pointer receiver so that I can make changes to struct fields? Is there an idiomatic way to do this?
// CountWriter is a type representing a writer that also counts
type CountWriter struct {
Count int
Output io.Writer
}
func (cw *CountWriter) Write(p []byte) (int, error) {
cw.Count++
return cw.Output.Write(p)
}
func takeAWriter(w io.Writer) {
w.Write([]byte("Testing"))
}
func main() {
boo := CountWriter{0, os.Stdout}
boo.Write([]byte("Hello\n"))
fmt.Printf("Count is incremented: %d", boo.Count)
takeAWriter(boo)
}
The code yields this error:
prog.go:27:13: cannot use boo (type CountWriter) as type io.Writer in argument to takeAWriter:
CountWriter does not implement io.Writer (Write method has pointer receiver)
It seems you can either satisfy the Writer
interface or have your changes made to the actual struct
. If I change the Write method to a value receiver (func (cw CountWriter) Write...
), I can avoid the error but the value does not increment. :(