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

huangapple go评论88阅读模式
英文:

How to copy/clone an interface pointer?

问题

我正在尝试复制一个作为interface{}接收的指针。有什么办法可以做到这一点吗?我尝试了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)
}

你可以在这里查看代码:http://play.golang.org/p/rFmJGrLVaa

英文:

I'm trying to make a copy of a pointer received as interface{}. Any idea how to do that? I've tried Reflect.Value.Interface() but it returns the pointer/ address itself instead to return its value (deference). I'm also wondering if there is a signifiant performance loss as I'm planning doing this kind of copy vs simple pointer 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)
}

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

答案1

得分: 5

你需要使用reflect.Indirect函数,并在修改s.field之前设置b的值。

以下是一段可工作的代码:

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

你可以在这里查看代码:https://play.golang.org/p/PShhvwXjdG

英文:

You need reflect.Indirect, and also to set b before changing s.field.

Here is some working code :

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

huangapple
  • 本文由 发表于 2015年10月9日 11:05:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/33029228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定