1

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'\n", string(input))
    rr.body = append(rr.body, input...)
    fmt.Printf("rr.body = '%s'\n", 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'\n", 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?

Elliot Chance
  • 5,526
  • 10
  • 49
  • 80
  • 7
    your receiver needs to be a pointer https://play.golang.org/p/zsF8mTtWpZ – mkopriva Mar 17 '17 at 00:34
  • Thank you! I had tried passing it by reference but it did the same thing. The fix was that Write() needed to be on the pointer: `*resultReceiver` – Elliot Chance Mar 17 '17 at 03:50

2 Answers2

1

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.

Conner
  • 723
  • 1
  • 8
  • 17
0

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

beiping96
  • 644
  • 3
  • 12