I cannot figure out why the following code is not working:
type Writer interface {
Write(input []byte) (int, error)
}
type resultReceiver struct {
body []byte
}
func (rr resultReceiver) Write(input []byte) (int, error) {
fmt.Printf("received '%s'
", string(input))
rr.body = append(rr.body, input...)
fmt.Printf("rr.body = '%s'
", string(rr.body))
return len(input), nil
}
func doWrite(w Writer) {
w.Write([]byte("foo"))
}
func main() {
receiver := resultReceiver{}
doWrite(receiver)
doWrite(receiver)
fmt.Printf("result = '%s'
", string(receiver.body))
}
https://play.golang.org/p/pxbgM8QVYB
I would expect to receive the output:
received 'foo'
rr.body = 'foo'
received 'foo'
rr.body = 'foofoo'
result = 'foofoo'
By instead it is not setting the resultReceiver.body
at all?
You are trying to change the underlying state of your resultReceiver which requires a pointer to the struct. You have a function instead of a method:
https://play.golang.org/p/zsF8mTtWpZ
Checkout Steve Fancia's talk on Go mistakes; Numbers 4 and 5, Functions vs Methods and Pointers vs Values respectively, will be a good refresher for you.
https://golang.org/doc/effective_go.html#pointers_vs_values
see Effective Go pointers vs values
by your way, the method to receive just a copy of the value