gpt4 book ai didi

Golang 对接口(interface)的反射 vs 指向接口(interface)的指针

转载 作者:IT王子 更新时间:2023-10-29 01:36:34 25 4
gpt4 key购买 nike

在gob用法的例子中http://golang.org/src/encoding/gob/example_interface_test.go他们提供了以下论点:将指针传递给接口(interface),以便 Encode 看到(并因此发送)接口(interface)类型的值。如果我们直接传递 p,它会看到具体类型。有关背景信息,请参阅博客文章“反射法则”。

我读过两遍反射法则,还有一篇相关的 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)的反射 vs 指向接口(interface)的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com