Why value stored in an interface is not addressable in Golang

后端 未结 4 558
不知归路
不知归路 2020-12-09 00:07

Citing the golang wiki (https://github.com/golang/go/wiki/MethodSets#interfaces):

\"The concrete value stored in an interface is not addressable, in the same way, th

4条回答
  •  时光取名叫无心
    2020-12-09 00:47

    Helpful info in go doc:https://golang.org/doc/faq#different_method_sets

    Even in cases where the compiler could take the address of a value to pass to the method, if the method modifies the value the changes will be lost in the caller. As an example, if the Write method of bytes.Buffer used a value receiver rather than a pointer, this code:

    var buf bytes.Buffer
    io.Copy(buf, os.Stdin)
    

    would copy standard input into a copy of buf, not into buf itself. This is almost never the desired behavior.

提交回复
热议问题