我想不通,为什么下面的代码不工作:为什么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' –