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

The*_*hat 5 go

我正在尝试将接收的指针复制为接口{}.知道怎么做吗?我已经尝试过Reflect.Value.Interface()但它返回指针/地址本身而不是返回它的值(deference).我也想知道是否存在显着的性能损失,因为我计划进行这种复制与简单的指针干扰.

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)
}
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/rFmJGrLVaa

Hec*_*orJ 5

您需要reflect.Indirect,并且还需要b在更改之前进行设置s.field

这是一些工作代码:

https://play.golang.org/p/PShhvwXjdG

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)
}
Run Code Online (Sandbox Code Playgroud)