我想不通,爲什麼下面的代碼不工作:爲什麼append不能與切片一起使用?
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
我希望收到輸出:
received 'foo'
rr.body = 'foo'
received 'foo'
rr.body = 'foofoo'
result = 'foofoo'
通過,而不是它不設置resultReceiver.body
在所有?
您的接收器需要成爲一個指針https://play.golang.org/p/zsF8mTtWpZ – mkopriva
謝謝!我曾嘗試通過引用傳遞它,但它做了同樣的事情。修復是Write()需要在指針上:'* resultReceiver' –