为什么 append 方法不能用于切片?

huangapple go评论78阅读模式
英文:

Why does append not work with slices?

问题

我无法弄清楚以下代码为什么不起作用:

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))
}

我期望输出如下:

received 'foo'
rr.body = 'foo'
received 'foo'
rr.body = 'foofoo'
result = 'foofoo'

但实际上它根本没有设置resultReceiver.body

英文:

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?

答案1

得分: 1

你正在尝试更改resultReceiver的底层状态,这需要一个指向结构体的指针。你使用的是一个函数而不是一个方法:

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

你可以查看Steve Fancia关于Go语言错误的演讲,其中的第4个和第5个话题,即"Functions vs Methods"和"Pointers vs Values",对你来说会是一个很好的复习材料。

英文:

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.

答案2

得分: 0

你好!以下是你要翻译的内容:

https://golang.org/doc/effective_go.html#pointers_vs_values

请查看《Effective Go》中的指针与值的比较。

通过你的方式,方法只接收值的副本。

英文:

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

huangapple
  • 本文由 发表于 2017年3月17日 08:26:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42847138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定