Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何复制/克隆接口指针?_Go - Fatal编程技术网

Go 如何复制/克隆接口指针?

Go 如何复制/克隆接口指针?,go,Go,我正在尝试复制作为接口{}接收的指针。你知道怎么做吗?我尝试了Reflect.Value.Interface(),但它返回指针/地址本身以返回其值(尊重)。我还想知道,在我计划进行这种复制而不是简单的指针遵从时,是否存在显著的性能损失 package main import "fmt" import "reflect" type str struct { field string } func main() { s := &str{field: "astr"}

我正在尝试复制作为接口{}接收的指针。你知道怎么做吗?我尝试了Reflect.Value.Interface(),但它返回指针/地址本身以返回其值(尊重)。我还想知道,在我计划进行这种复制而不是简单的指针遵从时,是否存在显著的性能损失

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