Go 如何复制/克隆接口指针?
我正在尝试复制作为接口{}接收的指针。你知道怎么做吗?我尝试了Reflect.Value.Interface(),但它返回指针/地址本身以返回其值(尊重)。我还想知道,在我计划进行这种复制而不是简单的指针遵从时,是否存在显著的性能损失Go 如何复制/克隆接口指针?,go,Go,我正在尝试复制作为接口{}接收的指针。你知道怎么做吗?我尝试了Reflect.Value.Interface(),但它返回指针/地址本身以返回其值(尊重)。我还想知道,在我计划进行这种复制而不是简单的指针遵从时,是否存在显著的性能损失 package main import "fmt" import "reflect" type str struct { field string } func main() { s := &str{field: "astr"}
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.ValueOf(a)
s.field = "changed field"
b := v.Interface()
fmt.Println(a, b)
}
您需要,并且在更改s.field
之前设置b
以下是一些工作代码:
如果您知道类型,为什么不使用类型断言?@JimB,但我不知道,这就是为什么存在接口{}。
package main
import "fmt"
import "reflect"
type str struct {
field string
}
func main() {
s := &str{field: "astr"}
a := interface{}(s)
v := reflect.Indirect(reflect.ValueOf(a))
b := v.Interface()
s.field = "changed field"
fmt.Println(a, b)
}