对结构字段进行永久更改,并满足Writer接口? [重复]

This question already has an answer here:

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
"))
    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. :(

https://play.golang.org/p/pEUwwTj0zrb

</div>

boo Doesn’t implement the interface because Write takes *CountWriter and not a CountWriter
However, &boo will be accepted by Write, so you have to pass it instead.