在gob使用示例中http://golang.org/src/encoding/gob/example_interface_test.go他们提供了以下论文:
将指针传递给接口(interface),以便 Encode 看到(并因此发送)接口(interface)类型的值。如果我们直接传递 p ,它将看到具体类型。请参阅博客文章“反射定律”了解背景信息。
我读过《反射(reflection)法则》两遍,还读过 Russ Cox 的一篇相关文章。但我找不到接口(interface)指针和接口(interface)之间的区别。
那么为什么通过指针它会看到接口(interface)类型的值,而没有指针它会看到(令我惊讶的是)具体类型?
最佳答案
在我看来,相关部分是 this :
Continuing, we can do this:
var empty interface{} empty = w
and our empty interface value empty will again contain that same pair, (tty, *os.File). That's handy: an empty interface can hold any value and contains all the information we could ever need about that value.
(添加强调)
当您将接口(interface)值分配给 interface{}
类型的值时,新值的“指向数据的指针”部分不会指向旧值,而是指向数据旧值指向。我们可以用一些不安全
代码来证明这一点:
type iface struct {
Type, Data unsafe.Pointer
}
var r io.Reader = &bytes.Buffer{}
var i interface{} = r
rr := *(*iface)(unsafe.Pointer(&r))
ii := *(*iface)(unsafe.Pointer(&i))
fmt.Printf("%v\n", ii.Data == rr.Data) // Prints true.
另一方面,如果我们使用指针,它将指向接口(interface)值本身。所以现在 reflect
实际上可以看到,我们到底在谈论什么接口(interface)。例如:
var i2 interface{} = &r
ii2 := *(*iface)(unsafe.Pointer(&i2))
fmt.Printf("%v\n", ii2.Data == unsafe.Pointer(&r)) // Prints true.
Playground :http://play.golang.org/p/0ZEMdIFhIj
关于Golang 接口(interface)反射与接口(interface)指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971363/